diff --git a/day01cpp/main.cpp b/day01cpp/main.cpp index 237c8ce181774d991a9dbdd8cacf1a5fb9f199f1..1eff43ed63a364742b53e1e39a12f0756978e67e 100644 --- a/day01cpp/main.cpp +++ b/day01cpp/main.cpp @@ -1 +1,68 @@ -int main() {} +#include <algorithm> +#include <fstream> +#include <iostream> +#include <ranges> +#include <set> +#include <string> + +void part_a() { + std::ifstream data("data.txt"); + std::string line; + int sum = 0; + + while (std::getline(data, line)) { + int a = *std::ranges::find_if(line.begin(), line.end(), [](char c) { + return std::isdigit(c); + }) - '0'; + int b = *std::ranges::find_if(line.rbegin(), line.rend(), [](char c) { + return std::isdigit(c); + }) - '0'; + sum += a * 10 + b; + } + + std::cout << sum << std::endl; +} + +void part_b() { + std::ifstream data("data.txt"); + + constexpr std::array<std::string_view, 9> numbers + = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; + + std::string line; + uint32_t sum = 0; + + while (std::getline(data, line)) { + std::pair num_a { 0, line.size() }; + for (size_t index = 0; index < numbers.size(); ++index) { + auto offset = std::min(line.find(numbers[index]), line.find(std::to_string(index + 1))); + if (offset != line.npos && offset < num_a.second) { + num_a.first = index + 1; + num_a.second = offset; + } + } + + std::pair num_b { 0, -1 }; + for (size_t index = 0; index < numbers.size(); ++index) { + std::set found = { line.rfind(numbers[index]), line.rfind(std::to_string(index + 1)) }; + found.erase(line.npos); + + if (!found.empty()) { + auto offset = std::ranges::max(found); + if (static_cast<int>(offset) > num_b.second) { + num_b.first = index + 1; + num_b.second = offset; + } + } + } + + sum += num_a.first * 10 + num_b.first; + } + + std::cout << sum << std::endl; +} + +int main() { + part_a(); + part_b(); +}