AoC2023/day4/day4a.c
2023-12-05 14:58:08 +01:00

59 lines
1.4 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#define ROW_LENGTH 120
int main ()
{
FILE *input;
input = fopen("./input", "r");
int offset = 0;
char c;
int score = 0;
char row[ROW_LENGTH];
// for each card (row in file) (numbers start after :)
while (fgets(row, ROW_LENGTH, input) != NULL) {
int winningNumbers[10] = {0};
int hits = -1;
printf("%s\n", row);
// offset = (strchr(row, '|') - &row[0]) - 2;
offset = (strchr(row, ':') - &row[0] + 1);
int foundNumbers = 0;
for (int i = 0; row[offset + i] != '|'; i++) {
if (isdigit(row[offset + i])) {
while (isdigit(c = row[offset + i])) {
winningNumbers[foundNumbers] = winningNumbers[foundNumbers] * 10 + (c - '0');
i++;
}
i--;
printf("number %d: %d\n", foundNumbers, winningNumbers[foundNumbers]);
foundNumbers++;
}
}
offset = (strchr(row, '|') - &row[0] + 1);
for (int i = 0; row[offset + i] != '\n'; i++) {
if (isdigit(row[offset + i])) {
int num = 0;
while (isdigit(c = row[offset + i])) {
num = num * 10 + (c - '0');
i++;
}
for (int i = 0; i < 10; i++) {
if (num == winningNumbers[i]) hits++;
}
i--;
}
}
if (hits >= 0) score += (int)pow(2, hits);
printf("hits = %d\n", hits);
printf("Card score: %d\n", (int)pow(2, hits));
}
printf("Total score: %d\n", score);
}