Day 4 part 2 complete!

This commit is contained in:
Alexander Andreev 2023-12-04 18:21:52 +04:00
parent 6df6e7f36d
commit fcabbd7dec
Signed by: Arav
GPG Key ID: D22A817D95815393
3 changed files with 94 additions and 2 deletions

View File

@ -23,7 +23,7 @@ day3: day3/p1.c day3/p2.c
day4: day4/p1.c day4/p2.c
${CC} ${CFLAGS} $@/p1.c -o bin/$@p1
# ${CC} ${CFLAGS} $@/p2.c -o bin/$@p2
${CC} ${CFLAGS} $@/p2.c -o bin/$@p2
clean:
rm -f bin/day*p*

89
day4/p2.c Normal file
View File

@ -0,0 +1,89 @@
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#define STACK_SZ 256
int32_t parse_number(char *end);
int main(int argc, char **argv) {
FILE *input;
char *line = NULL;
size_t line_length = 0;
if (argc == 1 || argv[1][0] == '-')
input = stdin;
else if ((input = fopen(argv[1], "r")) == NULL) {
printf("Cannot open file %s\n", argv[1]);
return -1;
}
uint32_t total_copies = 0;
size_t winning_numbers_len = 0;
int8_t *winning_numbers = NULL;
char *colon_pos = NULL, *pipe_pos = NULL;
uint32_t stack[STACK_SZ] = {0};
uint8_t stack_pos = 0;
while (getline(&line, &line_length, input) != -1) {
colon_pos = strchr(line, ':');
pipe_pos = strchr(line, '|');
if (winning_numbers == NULL) {
winning_numbers_len = (pipe_pos - colon_pos - 2) / 3;
winning_numbers = (int8_t *) calloc(winning_numbers_len, sizeof(int8_t));
}
for (size_t i = 0, wl_pos = (size_t)colon_pos+4; i < winning_numbers_len; ++i, wl_pos += 3) {
winning_numbers[i] = parse_number((char *)(wl_pos-1));
}
uint32_t card_copies = 1 + stack[stack_pos++];
total_copies += card_copies;
size_t old_sp = stack_pos;
for (char *n_pos = pipe_pos + 4;; n_pos += 3) {
int8_t n = parse_number(n_pos-1);
for (size_t i = 0; i < winning_numbers_len; ++i) {
if (n != winning_numbers[i])
continue;
stack[stack_pos++] += card_copies;
break;
}
if (*n_pos == '\n')
break;
}
stack_pos = old_sp;
memset(line, 0, line_length);
}
free(winning_numbers);
printf("%d\n", total_copies);
return 0;
}
int32_t parse_number(char *end) {
int32_t num = 0;
for (size_t n = 1;; n *= 10) {
if (*end>>4 != 0x3)
break;
num += (*end&0xf) * n;
--end;
}
return num;
}

5
test
View File

@ -13,4 +13,7 @@ echo "Day 2 with test data part 1 $(test_case 2 1 "test" "8"), and part 2 $(test
echo "Day 2 with my data part 1 $(test_case 2 1 "my" "2727"), and part 2 $(test_case 2 2 "my" "56580").";
echo "Day 3 with test data part 1 $(test_case 3 1 "test" "4361"), and part 2 $(test_case 3 2 "test" "467835").";
echo "Day 3 with my data part 1 $(test_case 3 1 "my" "550934"), and part 2 $(test_case 3 2 "my" "81997870").";
echo "Day 3 with my data part 1 $(test_case 3 1 "my" "550934"), and part 2 $(test_case 3 2 "my" "81997870").";
echo "Day 4 with test data part 1 $(test_case 4 1 "test" "13"), and part 2 $(test_case 4 2 "test" "30").";
echo "Day 4 with my data part 1 $(test_case 4 1 "my" "21959"), and part 2 $(test_case 4 2 "my" "5132675").";