QUOTE: Be your own kind of beautiful.

aoc_2024_4_1.c - aoc - Advent of Code challenges

aoc

Advent of Code challenges
git clone git@soophie.de:/srv/git/aoc
log | files | refs

aoc_2024_4_1.c (1413B)


      1 #include <stdbool.h>
      2 #include <string.h>
      3 
      4 #define NELEMS(x) (int) (sizeof(x) / sizeof((x)[0]))
      5 #define MATCH "XMAS"
      6 
      7 typedef struct {
      8   int y;
      9   int x;
     10 } dir_t;
     11 
     12 const dir_t DIRS[8] = {
     13   {  1,  0 },
     14   { -1,  0 },
     15   {  0,  1 },
     16   {  0, -1 },
     17   {  1,  1 },
     18   {  1, -1 },
     19   { -1,  1 },
     20   { -1, -1 },
     21 };
     22 
     23 long perform(char *data) {
     24   int len = strlen(data);
     25   int rows = 0;
     26   int cols = 0;
     27   for (int i = 0; i < len; i++) {
     28     char c = data[i];
     29     if (c == '\n') {
     30       if (rows == 0) {
     31         cols = i;
     32       }
     33       rows++;
     34     }
     35   }
     36   char grid[rows][cols];
     37   for (int i = 0; i < len; i++) {
     38     char c = data[i];
     39     if (c == '\n') {
     40       continue;
     41     }
     42     int y = i / (cols + 1);
     43     int x = i % (cols + 1);
     44     grid[y][x] = data[i];
     45   }
     46   int count = 0;
     47   for (int y = 0; y < rows; y++) {
     48     for (int x = 0; x < cols; x++) {
     49       for (int i = 0; i < NELEMS(DIRS); i++) {
     50         dir_t dir = DIRS[i];
     51         bool is_match = true;
     52         for (int j = 0; j < (int) strlen(MATCH); j++) {
     53           int ry = y + j * dir.y;
     54           int rx = x + j * dir.x;
     55           if (ry < 0 || ry >= rows || rx < 0 || rx >= cols) {
     56             is_match = false;
     57             break;
     58           }
     59           char c = grid[ry][rx];
     60           if (c != MATCH[j]) {
     61             is_match = false;
     62             break;
     63           }
     64         }
     65         if (is_match) {
     66           count++;
     67         }
     68       }
     69     }
     70   }
     71   return count;
     72 }