#include "utils.h" #include "json.hpp" #include "settings.h" #include #include #include #include #include #include #include nlohmann::json utils::loadJson(const std::string& path) { std::ifstream f(path); nlohmann::json j; f >> j; return j; } nlohmann::json utils::loadJson(const std::string& type, const std::string& name) { for(auto data : utils::loadAllJson(settings::getString(type))) { if(data["name"] == name) { return data; } } throw std::invalid_argument("Unknown name: `" + name + "' for type `" + type + "'."); } void utils::saveJson(const nlohmann::json& data, const std::string& path) { std::ofstream f(path); f << std::setw(4) << data << std::endl; } static std::map> cache; std::vector utils::loadAllJson(const std::string& directory) { if(cache.contains(directory)) { return cache[directory]; } std::vector ret; for(auto path : std::filesystem::recursive_directory_iterator(directory)) { if(path.path().extension() == ".json") { ret.push_back(utils::loadJson(path.path())); } } cache[directory] = ret; return ret; } // Accepts coins formatted "X Yp" where X is an integer and Y is any of c, s, e, g, p. int utils::coins2copper(const std::string& coins) { int num = std::stoi(coins.substr(0, coins.find(" "))); std::string denomination(coins.substr(coins.find(" ") + 1)); if(! cpValue.contains(denomination)) { throw std::invalid_argument("Unknown coin type: " + denomination); } return num * cpValue.at(denomination); } // Greedily selects highest coin values to minimize total number of coins // Returns a vector of pairs mapping coin type to coint std::vector> utils::copper2coins(int coppers) { std::vector> ret; while(coppers > 0) { // Find the largest denomination in cpValue under coppers std::pair largest("", 0); for(auto pair : cpValue) { if(pair.second <= coppers && pair.second > largest.second) { largest = pair; } } std::pair amnt(largest.first, coppers / largest.second); coppers -= amnt.second * largest.second; ret.push_back(amnt); } return ret; } std::string utils::getCostString(int coppers) { std::vector parts; for(auto pair : utils::copper2coins(coppers)) { parts.push_back(std::to_string(pair.second) + " " + pair.first); } return utils::join(parts, ", "); }