From ef3b84a16bb5c6adcd3aa4f7e67243f29e301231 Mon Sep 17 00:00:00 2001 From: Nick Krichevsky Date: Tue, 1 Dec 2020 00:33:28 -0500 Subject: [PATCH] Add day1 solution --- day1/day1.cpp | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 day1/day1.cpp diff --git a/day1/day1.cpp b/day1/day1.cpp new file mode 100644 index 0000000..47c900d --- /dev/null +++ b/day1/day1.cpp @@ -0,0 +1,71 @@ +#include +#include +#include +#include +#include + +constexpr int TARGET_NUM = 2020; + +/** + * Read the input and get it as a set of integers + * @param filename The filename to read from + * @return std::set A set of the numbers in the input + */ +std::set read_input(const std::string &filename) +{ + std::set input; + std::string line; + std::ifstream file(filename); + + while (std::getline(file, line)) + { + int num = std::stoi(line); + input.insert(num); + } + + return input; +} + +int part1(const std::set &inputs) +{ + for (int num : inputs) + { + int desired = TARGET_NUM - num; + if (inputs.find(desired) != inputs.end()) + { + return desired * num; + } + } + + throw "Does not contain solution"; +} + +int part2(const std::set &inputs) +{ + for (int num : inputs) + { + for (int num2 : inputs) + { + int desired = TARGET_NUM - (num + num2); + if (inputs.find(desired) != inputs.end()) + { + return desired * num2 * num; + } + } + } + + throw std::runtime_error("Does not contain solution"); +} + +int main(int argc, const char *argv[]) +{ + if (argc != 2) + { + std::cerr << "./day1 " << std::endl; + return 1; + } + + std::set inputs = read_input(argv[1]); + std::cout << part1(inputs) << std::endl; + std::cout << part2(inputs) << std::endl; +}