AoC2024/9/main.c

90 lines
1.8 KiB
C
Raw Permalink Normal View History

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<stdbool.h>
int main ()
{
// figure out data dimensions
FILE *input = fopen("./input", "r");
int width = 0;
bool flip = 1;
unsigned int dataSum = 0;
unsigned int dataID = 0;
int dataSlot = 0;
for (char c = fgetc(input); c != EOF && c != '\n'; c = fgetc(input)) {
dataSum += c - '0';
width++;
}
rewind(input);
printf("Length: %d\ndataSum: %u\n", width, dataSum);
unsigned int *memory = malloc(dataSum * sizeof(int));
// -1 represents empty memory
for (int i = 0; i < dataSum; i++) {
memory[i] = -1;
}
// time to fill the array
for (int i = 0; i < width; i++) {
char c = fgetc(input);
if (c == EOF) {
printf("breakbreakbreak!\n");
break;
}
// fan ska ju bara vara varannan som är data, resten free space
// flipflopflipflop ^
for (int j = 0; j < (c - '0'); j++) {
if (flip) {
memory[dataSlot] = dataID;
printf("%u", memory[dataSlot]);
} else {
memory[dataSlot] = -1;
printf(".");
}
dataSlot++;
}
if (flip)
dataID++;
flip ^= true;
}
fclose(input);
printf("\n");
// it's compacting time!
// start at end of array, save id, overwrite, put in first free spot
int lastWrite = 0;
for (int i = dataSum - 1; i >= 0; i--) {
if (memory[i] == -1)
continue;
if (lastWrite >= i)
goto exitDaLoop;
int tmp = memory[i];
memory[i] = -1;
for (; lastWrite < dataSum; lastWrite++) {
if (memory[lastWrite] == -1) {
memory[lastWrite] = tmp;
break;
}
}
}
exitDaLoop:
for (int i = 0; i < dataSum; i++) {
if (memory[i] != -1)
printf("%u", memory[i]);
else
printf(".");
}
// now hash time
unsigned long int hash = 0;
for (int i = 0; i < dataSum; i++) {
if (memory[i] != -1)
hash += memory[i] * i;
}
free(memory);
printf("\n%lu\n", hash);
}