AoC2023/day5/day5a.c
2023-12-05 20:22:09 +01:00

98 lines
2.5 KiB
C

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <math.h>
#include <ctype.h>
#define SEEDS 20
void remap(FILE *input, char *row, int *seedArray, int seed, int remaps);
// för varje seed:
// är den i rangen seed to soil? if so, = soil + i
// testa varje range så och reassigna on hit, sen spara i location array
// Lägsta i array är svaret
// vi har:
// lista med seed
// 7 maps
// lagra seeds i array
// array som säger om seed är omvandlat i current map
// för varje rad i map, kolla varje seed (om det ej omvandlat)
// vid nästa map, nolla omvandlatArray
int main()
{
unsigned int seedArray[SEEDS] = {0};
char row[250];
char c;
FILE *input;
input = fopen("./input", "r");
int seed = 0;
while (c = fgetc(input) != '\n') {
while (isdigit(c = fgetc(input))) {
seedArray[seed] = seedArray[seed] * 10 + (c - '0');
}
fseek(input, -1L, SEEK_CUR); // currently stepping two steps forward so yeah
if (seedArray[seed] != 0) seed++;
}
// for (int i = 0; i < seed; i++)
// printf("Seed %d: %u\n", i + 1, seedArray[i]);
int remaps = 1;
while (fgets(row, 250, input) != NULL) {
if (strstr(row, "map")) {
remap(input, row, seedArray, seed, remaps);
remaps++;
}
}
int i = 0;
int min = UINT_MAX;
for (; i < seed; i++) {
if (seedArray[i] < min) min = seedArray[i];
printf("Seed %d: %u\n", i + 1, seedArray[i]);
}
printf("%u\n", min);
}
void remap(FILE *input, char *row, int *seedArray, int seed, int remaps)
{
int seedDone[20] = {0};
while (fgets(row, 250, input) != NULL && row[0] != '\n') {
unsigned int i = 0;
while (!isdigit(row[i])) i++;
unsigned int dest = 0;
for (; isdigit(row[i]); i++) {
dest = dest * 10 + row[i] - '0';
}
while (!isdigit(row[i])) i++;
unsigned int source = 0;
for (; isdigit(row[i]); i++) {
source = source * 10 + row[i] - '0';
}
while (!isdigit(row[i])) i++;
unsigned int range = 0;
for (; isdigit(row[i]); i++) {
range = range * 10 + row[i] - '0';
}
range -= 1;
// printf("Dest: %u, Source: %u, range: %u\n", dest, source, range + 1);
for (int i = 0; i < seed; i++) {
if (seedDone[i] == 0 && seedArray[i] >= source && seedArray[i] <= source + range) {
// printf("Seed %d: %u is in range, moving to %u\n", i + 1, seedArray[i], dest + seedArray[i] - source);
seedArray[i] = dest + seedArray[i] - source;
// printf("Seed %d: %u\n", i + 1, seedArray[i]);
seedDone[i] = 1;
}
}
}
// printf("Remap %d done.\n", remaps);
}