From 17d6a4cb508cc9d5aa806a1e1df24bdd14621e41 Mon Sep 17 00:00:00 2001 From: Federico Igne Date: Fri, 1 Dec 2023 23:56:13 +0100 Subject: aoc(2301): Trebuchet?! --- 2023/01/src/part1.cpp | 37 +++++++++++++++++++++++++ 2023/01/src/part2.cpp | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 114 insertions(+) create mode 100644 2023/01/src/part1.cpp create mode 100644 2023/01/src/part2.cpp (limited to '2023/01/src') diff --git a/2023/01/src/part1.cpp b/2023/01/src/part1.cpp new file mode 100644 index 0000000..3034d43 --- /dev/null +++ b/2023/01/src/part1.cpp @@ -0,0 +1,37 @@ +#include +#include + +template +int search(Iter from, Iter to) +{ + while(from < to) + { + char c = *(from++); + if (std::isdigit(c)) + { + return c - '0'; + } + } + return 0; +} + +int main(void) +{ + int answer{}; + + std::ifstream input{ "./resources/input.txt" }; + if (input) + { + std::string line; + while(not std::getline(input, line).eof()) + { + answer += 10 * search(line.begin(), line.end()); + answer += search(line.rbegin(), line.rend()); + } + + } + input.close(); + + std::cout << answer << std::endl; + return 0; +} diff --git a/2023/01/src/part2.cpp b/2023/01/src/part2.cpp new file mode 100644 index 0000000..77b5067 --- /dev/null +++ b/2023/01/src/part2.cpp @@ -0,0 +1,77 @@ +#include +#include +#include + +int update(int status[9], char c) +{ + static const std::vector words{ + "one", "two", "three", "four", "five", + "six", "seven", "eight", "nine" + }; + + int ret{}; + + for (int a{}; a < words.size(); ++a) + { + if (words[a][status[a]] == c) + { + ++status[a]; + } + else + { + status[a] = words[a][0] == c; + } + + if (status[a] == words[a].size()) + { + ret = a+1; + } + } + return ret; +} + +int search(const std::string& line) +{ + int status[9]{}; + + int fst{}, lst{}; + for (char c : line) + { + int d = update(status, c); + if (std::isdigit(c)) + { + d = c - '0'; + } + + if (d > 0) + { + if (fst <= 0) + { + fst = d; + } + lst = d; + } + } + return fst * 10 + lst; +} + + +int main(void) +{ + int answer{}; + + std::ifstream input{ "./resources/input.txt" }; + if (input) + { + std::string line; + while(not std::getline(input, line).eof()) + { + answer += search(line); + } + + } + input.close(); + + std::cout << answer << std::endl; + return 0; +} -- cgit v1.2.3