diff --git a/userspace/aoc2023/CMakeLists.txt b/userspace/aoc2023/CMakeLists.txt index 8d97095ca2..d21ce7beba 100644 --- a/userspace/aoc2023/CMakeLists.txt +++ b/userspace/aoc2023/CMakeLists.txt @@ -6,6 +6,7 @@ set(AOC2023_PROJECTS day1 day2 day3 + day4 ) set(BANAN_AOC2023_BIN ${BANAN_BIN}/aoc2023) diff --git a/userspace/aoc2023/day4/CMakeLists.txt b/userspace/aoc2023/day4/CMakeLists.txt new file mode 100644 index 0000000000..f934e8a131 --- /dev/null +++ b/userspace/aoc2023/day4/CMakeLists.txt @@ -0,0 +1,22 @@ +cmake_minimum_required(VERSION 3.26) + +project(aoc2023_day4 CXX) + +set(SOURCES + main.cpp +) + +add_executable(aoc2023_day4 ${SOURCES}) +target_compile_options(aoc2023_day4 PUBLIC -O2 -g) +target_link_libraries(aoc2023_day4 PUBLIC libc ban) + +add_dependencies(aoc2023_day4 libc-install ban-install) + +add_custom_target(aoc2023_day4-install + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/aoc2023_day4 ${BANAN_AOC2023_BIN}/day4 + DEPENDS aoc2023_day4 + DEPENDS aoc2023_always +) + +add_dependencies(aoc2023 aoc2023_day4) +add_dependencies(aoc2023-install aoc2023_day4-install) diff --git a/userspace/aoc2023/day4/main.cpp b/userspace/aoc2023/day4/main.cpp new file mode 100644 index 0000000000..1bc4ed36b1 --- /dev/null +++ b/userspace/aoc2023/day4/main.cpp @@ -0,0 +1,92 @@ +#include +#include +#include + +#include +#include + +static int matching_numbers(BAN::StringView line) +{ + ASSERT(line.size() == 117); + line = line.substring(0, line.size() - 1); + + auto winning_numbers = MUST(line.substring(10, 29).split(' ')); + auto your_numbers = MUST(line.substring(42).split(' ')); + + int matching = 0; + for (auto number : your_numbers) + if (winning_numbers.contains(number)) + matching++; + + return matching; +} + +int puzzle1(FILE* fp) +{ + int result = 0; + + char buffer[128]; + while (fgets(buffer, sizeof(buffer), fp)) + { + if (strncmp(buffer, "Card", 4)) + continue; + + int matching = matching_numbers(buffer); + int points = !!matching; + for (int i = 1; i < matching; i++) + points *= 2; + result += points; + } + + return result; +} + +int puzzle2(FILE* fp) +{ + struct Card + { + BAN::String line; + int count; + }; + + BAN::Vector cards; + + char buffer[128]; + while (fgets(buffer, sizeof(buffer), fp)) + if (strncmp(buffer, "Card", 4) == 0) + MUST(cards.emplace_back(BAN::StringView(buffer), 1)); + + int result = 0; + for (size_t i = 0; i < cards.size(); i++) + { + int matching = matching_numbers(cards[i].line); + for (int j = 0; j < matching; j++) + cards[i + j + 1].count += cards[i].count; + result += cards[i].count; + } + + return result; +} + +int main(int argc, char** argv) +{ + const char* file_path = "/usr/share/aoc2023/day4_input.txt"; + + if (argc >= 2) + file_path = argv[1]; + + FILE* fp = fopen(file_path, "r"); + if (fp == nullptr) + { + perror("fopen"); + return 1; + } + + printf("puzzle1: %d\n", puzzle1(fp)); + + fseek(fp, 0, SEEK_SET); + + printf("puzzle2: %d\n", puzzle2(fp)); + + fclose(fp); +}