From e20d6c62a12fe8f8598e01ba17b538c38aa0201d Mon Sep 17 00:00:00 2001 From: Shanti Chellaram Date: Sat, 23 Oct 2021 02:31:35 -0400 Subject: [PATCH] Solve Day 3 C++ --- c++/main.cpp | 2 +- c++/problem3.cpp | 42 ++++++++++++++++++++++++++++++++++++++++++ c++/solutions.hpp | 1 + 3 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 c++/problem3.cpp diff --git a/c++/main.cpp b/c++/main.cpp index 8b9216b..a85906e 100644 --- a/c++/main.cpp +++ b/c++/main.cpp @@ -11,7 +11,7 @@ int main(int argc, char *argv[]) { return 0; } int problem_number = stoi(string(argv[1])); - solution_fn solutions[] = {solve1, solve2}; + solution_fn solutions[] = {solve1, solve2, solve3}; auto x = solutions[problem_number-1]; auto answer = x(cin); cout << "Solution 1: " << answer.first << endl; diff --git a/c++/problem3.cpp b/c++/problem3.cpp new file mode 100644 index 0000000..2f986ea --- /dev/null +++ b/c++/problem3.cpp @@ -0,0 +1,42 @@ +#include +#include +#include + +#include "solutions.hpp" + +using namespace std; + +pair solve3(istream& input) { + vector my_map; + uint64_t width; + bool width_set = false; + for (string line; getline(input, line); ) { + my_map.push_back(line); + if (!width_set) { + width = line.length(); + width_set = true; + } + } + array, 5> slopes { { + {1, 1}, + {3, 1}, + {5, 1}, + {7, 1}, + {1, 2} + } }; + uint64_t product = 1; + uint64_t part1; + for (auto slope : slopes) { + uint64_t total_trees = 0; + for (auto pos = pair(0, 0); pos.second < my_map.size(); ) { + total_trees += (int) my_map[pos.second][pos.first] == '#'; + pos.first = (pos.first + slope.first) % width; + pos.second += slope.second; + } + product *= total_trees; + if (slope.first == 3 && slope.second == 1) { + part1 = total_trees; + } + } + return pair(to_string(part1), to_string(product)); +} diff --git a/c++/solutions.hpp b/c++/solutions.hpp index 1dc4825..fdf240c 100644 --- a/c++/solutions.hpp +++ b/c++/solutions.hpp @@ -9,3 +9,4 @@ typedef std::pair (*solution_fn)(std::istream&); DECL_SOLUTION(1) DECL_SOLUTION(2) +DECL_SOLUTION(3)