75 lines
1.6 KiB
C
75 lines
1.6 KiB
C
#include<stdlib.h>
|
|
#include<stdio.h>
|
|
#include<string.h>
|
|
#include<stdbool.h>
|
|
|
|
int xmas_detector(char **grid, int x, int y, int width)
|
|
{
|
|
int real_xmas = 0;
|
|
char MAS[3] = {'M', 'A', 'S'};
|
|
int dir[8][2] =
|
|
{{-1, -1}, {0, -1}, {1, -1}, {1, 0},
|
|
{1, 1}, {0, 1}, {-1, 1}, {-1, 0}};
|
|
for (int i = 0; i < 8; i++) {
|
|
if (x + dir[i][0] * 3 < 0 ||
|
|
y + dir[i][1] * 3 < 0 ||
|
|
x + dir[i][0] * 3 >= width ||
|
|
y + dir[i][1] * 3 >= width)
|
|
continue;
|
|
for (int j = 1; j <= 3; j++) {
|
|
// holy can you read that coordinate?
|
|
if (grid[x + dir[i][0] * j][y + dir[i][1] * j] != MAS[j - 1])
|
|
break;
|
|
else if (j == 3)
|
|
real_xmas++;
|
|
}
|
|
}
|
|
|
|
return real_xmas;
|
|
}
|
|
|
|
int main ()
|
|
{
|
|
// figure out data dimensions
|
|
FILE *input = fopen("./input", "r");
|
|
int width = 0;
|
|
int height = 1;
|
|
while (fgetc(input) != '\n') width++;
|
|
for (char c = fgetc(input); c != EOF; c = fgetc(input)) {
|
|
if (c == '\n')
|
|
height++;
|
|
}
|
|
rewind(input);
|
|
printf("Dimensions: %d x %d\n", width, height);
|
|
|
|
// make 2d array
|
|
char **grid = malloc(width * sizeof(char*));
|
|
grid[0] = malloc(width * height);
|
|
for (int i = 1; i < width; i++) {
|
|
grid[i] = grid[0] + i * height;
|
|
}
|
|
|
|
// put the data in the array
|
|
for (int i = 0; i < width; i++) {
|
|
for (int j = 0; j < height; j++) {
|
|
grid[i][j] = fgetc(input);
|
|
}
|
|
// skip newline
|
|
fgetc(input);
|
|
}
|
|
fclose(input);
|
|
|
|
// find x
|
|
int sum_xmas = 0;
|
|
for (int i = 0; i < width; i++) {
|
|
for (int j = 0; j < height; j++) {
|
|
if (grid[i][j] == 'X')
|
|
// confirm mas in all 8 dir
|
|
sum_xmas += xmas_detector(grid, i, j, width);
|
|
}
|
|
}
|
|
|
|
printf("total xmases: %d\n", sum_xmas);
|
|
free(grid[0]);
|
|
free(grid);
|
|
}
|