aoc/2015/day06/answer01.c

92 lines
2.0 KiB
C
Raw Permalink Normal View History

2024-07-05 19:55:39 -04:00
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
void turn_on(uint16_t grid[1000][1000], uint16_t x, uint16_t y) {
grid[x][y] = 1;
}
void turn_off(uint16_t grid[1000][1000], uint16_t x, uint16_t y) {
grid[x][y] = 0;
}
void toggle(uint16_t grid[1000][1000], uint16_t x, uint16_t y) {
if (grid[x][y] == 0)
grid[x][y] = 1;
else
grid[x][y] = 0;
}
void process_instruction(char *line_buffer,
char *delimiters,
uint16_t grid[1000][1000],
void (*operation)(uint16_t 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 i = x1; i <= x2; i++)
for (uint16_t j = y1; j <= y2; j++)
operation(grid, i, j);
}
int main() {
FILE *file = fopen("input", "r");
if (file == NULL) {
perror("Error opening file.");
return 1;
}
uint16_t 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 count = 0;
for (uint16_t i = 0; i <= 999; i++)
for (uint16_t j = 0; j <= 999; j++)
if (grid[i][j] == 1)
count++;
printf("count: %u\n", count);
return 0;
}