From df6b6dd888b8469a4228cea249aba7c369c6cc23 Mon Sep 17 00:00:00 2001 From: Rekai Musuka Date: Tue, 1 Dec 2020 21:31:03 -0600 Subject: [PATCH] feat: decrease complexity of 2020-12-01 p1 & p2 --- day_1/main.cpp | 76 ++++++++++++++++++++++++++++---------------------- 1 file changed, 43 insertions(+), 33 deletions(-) diff --git a/day_1/main.cpp b/day_1/main.cpp index 3c98604..d70b3fb 100644 --- a/day_1/main.cpp +++ b/day_1/main.cpp @@ -1,6 +1,7 @@ #include #include #include +#include int part_1(); int part_2(); @@ -11,19 +12,53 @@ int main() { } int part_1() { - std::vector vector; + std::unordered_map map; std::ifstream input("../input.txt"); std::string line; - while(std::getline(input, line)) { - int num = std::stoi(line); - vector.push_back(num); + int i = 0; + while (std::getline(input, line)) { + std::pair pair {std::stoi(line), i}; + map.insert(pair); + i++; } - for (int i : vector) { - for (int j : vector) { - if (i + j == 2020) { - std::cout << (i * j) << std::endl; + for (std::pair pair : map) { + int num = pair.first; + int compliment = 2020 - num; + if (map.contains(compliment)) { + std::cout << (num * compliment) << std::endl; + return 0; + } + } + + return 1; +} + + +int part_2() { + std::unordered_map map; + std::ifstream input("../input.txt"); + std::string line; + + int i = 0; + while (std::getline(input, line)) { + std::pair pair {std::stoi(line), i}; + map.insert(pair); + i++; + } + + for (std::pair first_pair : map) { + int num = first_pair.first; + int compliment = 2020 - num; + + // Still two other numbers we gotta find from here + for (std::pair second_pair : map) { + int second_num = second_pair.first; + int second_compliment = compliment - second_num; + + if (map.contains(second_compliment)) { + std::cout << (num * second_num * second_compliment) << std::endl; return 0; } } @@ -32,28 +67,3 @@ int part_1() { return 1; } - -int part_2() { - std::vector vector; - std::ifstream input("../input.txt"); - std::string line; - - while(std::getline(input, line)) { - int num = std::stoi(line); - vector.push_back(num); - } - - for (int i : vector) { - for (int j : vector) { - for (int k : vector) { - if (i + j + k == 2020) { - std::cout << (i * j * k) << std::endl; - return 0; - } - } - } - } - - return 1; -} -