From fb54beb2bef7fe6b0d4e524b03c61d3f94ffee09 Mon Sep 17 00:00:00 2001 From: jacopograndi Date: Thu, 6 Jan 2022 13:05:05 +0100 Subject: init --- day03/day03 | Bin 0 -> 83112 bytes day03/day03.cpp | 96 +++++ day03/day03_input.txt | 1000 ++++++++++++++++++++++++++++++++++++++++++++++ day03/day03_input_ez.txt | 12 + day03/makefile | 2 + 5 files changed, 1110 insertions(+) create mode 100755 day03/day03 create mode 100644 day03/day03.cpp create mode 100644 day03/day03_input.txt create mode 100644 day03/day03_input_ez.txt create mode 100644 day03/makefile (limited to 'day03') diff --git a/day03/day03 b/day03/day03 new file mode 100755 index 0000000..ccb1732 Binary files /dev/null and b/day03/day03 differ diff --git a/day03/day03.cpp b/day03/day03.cpp new file mode 100644 index 0000000..036cd07 --- /dev/null +++ b/day03/day03.cpp @@ -0,0 +1,96 @@ +#include +#include +#include +#include + +int bin_to_dec (std::string bin) { + int dec = 0, pow = 1; + for (std::size_t i=bin.size(); i > 0; i--) { + dec += pow * (bin[i-1] == '0' ? 0 : 1); + pow *= 2; + } + return dec; +} + +std::vector get_freq (std::vector bits) { + std::vector freq; + for (std::size_t i=0; i filter (std::vector bits, int inv, int sel) { + std::vector res; + auto freq = get_freq(bits); + + for (auto b : bits) { + int f = freq[sel] * inv; + if (f == 0) f += inv; + if ((f > 0 ? '0' : '1') == b[sel]) { + res.push_back(b); + } + } + + return res; +} + +int main (int argc, char *argv[]) { + if (argc != 2) return 1; + + std::string raw; + std::getline(std::ifstream(argv[1]), raw, '\0'); + + std::vector bits; + + while (1) { + auto token = raw.find("\n"); + if (token != std::string::npos) { + bits.push_back(raw.substr(0, token)); + raw = raw.substr(token+1); + } else { + if (raw.size() > 0) bits.push_back(raw); + break; + } + } + + auto freq = get_freq(bits); + + std::string gamma = "", epsilon = ""; + for (std::size_t i=0; i 0 ? "1" : "0"; + epsilon += freq[i] > 0 ? "0" : "1"; + } + + int g = bin_to_dec(gamma); + int e = bin_to_dec(epsilon); + std::cout << "power level " << e*g << ", " + << "epsilon " << e << " (" << epsilon << "), " + << "gamma " << g << " (" << gamma << ")" << std::endl; + + std::vector o2 = bits; + for (std::size_t i=0; i co2 = bits; + for (std::size_t i=0; i