#include #include #include #include #include #include constexpr std::size_t bSize = 12; const std::vector& readToString(const std::string& path); const void getGammaEpsilon(std::bitset& g, std::bitset& e, const std::vector& v); const void filterCommonBit(int bit, const std::bitset& f, std::vector& v); std::string filterCommonBinary(bool common, std::vector v); int main() { std::vector inputs = readToString("../input/03.txt"); std::bitset o{filterCommonBinary(true, inputs)}; std::bitset c{filterCommonBinary(false, inputs)}; std::cout << o.to_ulong() * c.to_ulong() << std::endl; return 0; } const std::vector& readToString(const std::string& path) { std::ifstream inputFile(path); std::string input; static std::vector inputs; while(std::getline(inputFile, input)) inputs.push_back(input); inputFile.close(); return inputs; } const void getGammaEpsilon(std::bitset& g, std::bitset& e, const std::vector& v) { int bitOccurence [bSize]{}; for(const auto& el : v) for(int b = 0; b < bSize; b++) bitOccurence[b] += el[b] - 48; for(int b = 0; b < bSize; b++) g.set(bSize-b-1, bitOccurence[b] >= round((float) v.size()/2)); e = ~g; } const void filterCommonBit(int bit, const std::bitset& f, std::vector& v) { std::vector nv; for(int i = 0; i < v.size(); i++) { if(f[bSize-bit-1] == v[i][bit] - 48) nv.push_back(v[i]); } v.clear(); for(const auto& e : nv) v.push_back(e); } std::string filterCommonBinary(bool common, std::vector v) { std::bitset g, e; for(int b = 0; b < bSize; b++) { getGammaEpsilon(g, e, v); filterCommonBit(b, common ? g : e, v); if(v.size() == 1) return v[0]; } return ""; }