finish day 3

This commit is contained in:
2025-12-03 15:32:55 -05:00
parent 05a5bc27ad
commit debf18936b
5 changed files with 289 additions and 1 deletions

79
day3.cpp Normal file
View File

@@ -0,0 +1,79 @@
//
// Created by Grant Horner on 12/3/25.
//
#include <ranges>
#include <string>
#include <fstream>
#include <sstream>
#include "doctest.h"
namespace day3 {
const std::string sample = "987654321111111\n"
"811111111111119\n"
"234234234234278\n"
"818181911112111\n";
auto split_into_banks(const std::string_view input) {
return std::views::split(input, '\n')
| std::views::filter([](const auto &s) {
return !s.empty();
})
| std::views::transform([](const auto &x) {
return std::string_view(x);
});
}
uint64_t solve(const std::string_view input, uint8_t num_batteries) {
uint64_t sum = 0;
for (auto split: split_into_banks(input)) {
uint64_t bank = 0;
size_t largest_index = 0;
for (size_t i = num_batteries; i > 0; i--) {
const auto num_reserved = i - 1;
const auto substr_len = split.size() - largest_index - num_reserved;
const auto not_last = split.substr(largest_index, substr_len);
size_t temp_largest_index = 0;
uint8_t largest = 0;
for (size_t j = 0; j < not_last.size(); j++) {
if (const char c = not_last[j]; c > largest) {
largest = c;
temp_largest_index = 1 + j;
}
}
largest_index += temp_largest_index;
bank += (largest - '0') * std::pow(10, i - 1);
}
sum += bank;
}
return sum;
}
TEST_SUITE_BEGIN("Day 3");
TEST_CASE("solve first sample") {
CHECK(solve(sample, 2) == 357);
}
TEST_CASE("solve first puzzle") {
std::ifstream input("day3input.txt");
std::stringstream buf;
buf << input.rdbuf();
CHECK(solve(buf.view(),2) == 17095);
}
TEST_CASE("solve second sample") {
CHECK(solve(sample, 12) == 3121910778619);
}
TEST_CASE("solve second input") {
std::ifstream input("day3input.txt");
std::stringstream buf;
buf << input.rdbuf();
CHECK(solve(buf.view(), 12) == 168794698570517);
}
TEST_SUITE_END();
}