AOC2023: implement day4

This commit is contained in:
Bananymous 2023-12-04 17:51:27 +02:00
parent 3ed25425a3
commit 41f8974080
3 changed files with 115 additions and 0 deletions

View File

@ -6,6 +6,7 @@ set(AOC2023_PROJECTS
day1
day2
day3
day4
)
set(BANAN_AOC2023_BIN ${BANAN_BIN}/aoc2023)

View File

@ -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)

View File

@ -0,0 +1,92 @@
#include <BAN/Vector.h>
#include <BAN/String.h>
#include <BAN/StringView.h>
#include <stdio.h>
#include <string.h>
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<Card> 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);
}