refactor utils

This commit is contained in:
2025-12-04 22:12:32 -05:00
parent 9282b3d531
commit 4b1da89690
5 changed files with 54 additions and 64 deletions

View File

@@ -5,11 +5,11 @@
#include <cassert>
#include <charconv>
#include <ranges>
#include <fstream>
#include <sstream>
#include "doctest.h"
#include "utils.h"
namespace day1 {
enum Direction {
L = 'L',
R = 'R',
@@ -27,15 +27,17 @@ Instruction parse_instruction(std::string_view line) {
std::from_chars(&line[1], line.data() + line.size(), amount);
return Instruction{direction, amount};
}
}
template<>
struct std::formatter<Instruction> : std::formatter<string_view> {
static auto format(const Instruction &i, std::format_context &ctx) {
struct std::formatter<day1::Instruction> : std::formatter<string_view> {
static auto format(const day1::Instruction &i, std::format_context &ctx) {
return std::format_to(ctx.out(), "Instruction[direction: {}, amount: {}]", static_cast<char>(i.direction),
i.amount);
}
};
namespace day1 {
const std::string sample =
"L68\n"
"L30\n"
@@ -79,9 +81,9 @@ uint32_t solve_first(const std::string &input) {
uint32_t spins = 0;
for (const auto instr:
std::views::split(input, '\n')
| std::views::transform([](auto s) { return std::string_view(s); })
| std::views::filter([](const std::string_view s) { return !s.empty(); })
std::views::split(std::string_view{input}, '\n')
| std::views::transform(utils::to_string_view)
| std::views::filter(utils::non_empty)
| std::views::transform(parse_instruction)
) {
if (spin(value, instr)) {
@@ -96,11 +98,7 @@ uint32_t solve_first(const std::string &input) {
TEST_SUITE_BEGIN("Day 1");
TEST_CASE("puzzle 1") {
CHECK(solve_first(sample) == 3);
std::ifstream input("day1input.txt");
CHECK(input.is_open());
std::stringstream buffer;
buffer << input.rdbuf();
CHECK(solve_first(buffer.str()) == 1158);
CHECK(solve_first(utils::read_file("day1input.txt")) == 1158);
}
uint32_t solve_second(const std::string &input) {
@@ -108,9 +106,9 @@ uint32_t solve_second(const std::string &input) {
uint32_t spins = 0;
for (const auto instr:
std::views::split(input, '\n')
| std::views::transform([](auto s) { return std::string_view(s); })
| std::views::filter([](const std::string_view s) { return !s.empty(); })
std::views::split(std::string_view{input}, '\n')
| std::views::transform(utils::to_string_view)
| std::views::filter(utils::non_empty)
| std::views::transform(parse_instruction)
) {
spins += spin2(value, instr);
@@ -122,11 +120,8 @@ uint32_t solve_second(const std::string &input) {
TEST_CASE("puzzle 2") {
CHECK(solve_second(sample) == 6);
std::ifstream input("day1input.txt");
CHECK(input.is_open());
std::stringstream buffer;
buffer << input.rdbuf();
CHECK(solve_second(buffer.str()) == 6860);
CHECK(solve_second(utils::read_file("day1input.txt")) == 6860);
}
TEST_SUITE_END();
}