aoc2023/day5/p1.c

83 lines
2.0 KiB
C

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
inline uint64_t parse_number(const char *end);
int main(int argc, char **argv) {
FILE *input;
char *line = NULL;
size_t line_buf_length = 0;
if (argc == 1 || argv[1][0] == '-')
input = stdin;
else if ((input = fopen(argv[1], "r")) == NULL) {
fprintf(stderr, "Cannot open file %s\n", argv[1]);
return -1;
}
getline(&line, &line_buf_length, input);
char *colon_pos = strchr(line, ':');
size_t data_len = 0;
for (char *space_pos = colon_pos+1; space_pos != NULL; space_pos = strchr(space_pos, ' ')) {
data_len++;
space_pos++;
}
uint64_t *data = (uint64_t *) calloc(data_len, sizeof(uint64_t));
bool *data_v = (bool *) calloc(data_len, sizeof(bool));
for (size_t i = 0, seeds_pos = (size_t) colon_pos+2;; seeds_pos++) {
while (*(char *)(seeds_pos)>>4 == 0x3) seeds_pos++;
data[i++] = parse_number((char *)(seeds_pos-1));
if (*(char *)seeds_pos == '\n')
break;
}
while (getline(&line, &line_buf_length, input) != -1) {
if (line[0]>>4 != 0x3) {
for (size_t i = 0; i < data_len; ++i)
data_v[i] = false;
continue;
}
uint64_t dst = 0, src = 0, rng = 0;
sscanf(line, "%lu %lu %lu\n", &dst, &src, &rng);
for (size_t i = 0; i < data_len; ++i)
if (!data_v[i] && data[i] >= src && data[i] < src+rng) {
data[i] = dst + (data[i] - src);
data_v[i] = true;
}
memset(line, 0, line_buf_length);
}
uint64_t lowest_loc_n = INT32_MAX;
for (size_t i = 0; i < data_len; ++i)
lowest_loc_n = (data[i] < lowest_loc_n) ? data[i] : lowest_loc_n;
printf("%lu\n", lowest_loc_n);
return 0;
}
inline uint64_t parse_number(const char *end) {
uint64_t num = 0;
for (size_t m = 1;; m *= 10) {
if (*end>>4 != 0x3)
break;
num += (*end&0xf) * m;
--end;
}
return num;
}