aoc/2015/day06/answer02.c
2024-07-05 19:55:39 -04:00

89 lines
1.9 KiB
C

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
void turn_on(float grid[1000][1000], uint16_t x, uint16_t y) {
grid[x][y] += 1;
}
void turn_off(float grid[1000][1000], uint16_t x, uint16_t y) {
if (grid[x][y] > 0)
grid[x][y] -= 1;
}
void toggle(float grid[1000][1000], uint16_t x, uint16_t y) {
grid[x][y] += 2;
}
void process_instruction(char *line_buffer,
char *delimiters,
float grid[1000][1000],
void (*operation)(float grid[1000][1000], uint16_t, uint16_t)) {
uint16_t x1, x2, y1, y2;
char *token;
token = strtok(NULL, delimiters);
x1 = atoi(token);
token = strtok(NULL, delimiters);
y1 = atoi(token);
token = strtok(NULL, delimiters); //ignore the word "through"
token = strtok(NULL, delimiters);
x2 = atoi(token);
token = strtok(NULL, delimiters);
y2 = atoi(token);
for (uint16_t x = x1; x <= x2; x++)
for (uint16_t y = y1; y <= y2; y++)
operation(grid, x, y);
}
int main() {
FILE *file = fopen("input", "r");
if (file == NULL) {
perror("Error opening file.");
return 1;
}
float grid[1000][1000] = {0};
char delimiters[] = " ,";
char *token;
char line_buffer[256];
while (fgets(line_buffer, sizeof(line_buffer), file) != NULL) {
token = strtok(line_buffer, delimiters);
if (!strcmp(token, "toggle")) {
process_instruction(line_buffer, delimiters, grid, toggle);
continue;
}
if (!strcmp(token, "turn")) {
token = strtok(NULL, delimiters);
if (!strcmp(token, "on")) {
process_instruction(line_buffer, delimiters, grid, turn_on);
continue;
}
if (!strcmp(token, "off")) {
process_instruction(line_buffer, delimiters, grid, turn_off);
continue;
}
}
}
if (ferror(file)) {
perror("main: Error reading from file.");
return 1;
}
fclose(file);
uint32_t brightness = 0;
for (uint16_t x = 0; x <= 999; x++)
for (uint16_t y = 0; y <= 999; y++)
brightness += grid[x][y];
printf("brightness: %u\n", brightness);
return 0;
}