GAME: Play the number guessing game -> PLAY NOW

aoc_2024_2_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_2_1.c (1367B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <stdbool.h>
      4 #include <string.h>
      5 #include <ctype.h>
      6 
      7 #define ROW_SIZE 50
      8 
      9 typedef enum {
     10   DIR_NIL = 0,
     11   DIR_INC = 1,
     12   DIR_DEC = 2,
     13 } dir_t;
     14 
     15 long perform(char *data) {
     16   int len = strlen(data);
     17   int ln = 0;
     18   int sum = 0;
     19   int size = 0;
     20   int row[ROW_SIZE];
     21   for (int i = 0; i < len;) {
     22     char c = data[i];
     23     if (isdigit(c)) {
     24       char *end = NULL;
     25       row[size++] = strtol(data + i, &end, 10);
     26       i += end - (data + i);
     27       continue;
     28     }
     29     if (c == '\n') {
     30       bool unsafe = false;
     31       int *prev = NULL;
     32       dir_t dir = DIR_NIL;
     33       for (int j = 0; j < size; j++) {
     34         int *num = &row[j];
     35         if (prev != NULL) {
     36           // check 1. criteria
     37           dir_t next_dir = DIR_NIL;
     38           if (*num > *prev) {
     39             next_dir = DIR_INC;
     40           }
     41           if (*num < *prev) {
     42             next_dir = DIR_DEC;
     43           }
     44           if (dir != DIR_NIL && next_dir != dir) {
     45             unsafe = true;
     46             break;
     47           }
     48           dir = next_dir;
     49           // check 2. criteria
     50           int delta = abs(*num - *prev);
     51           if (delta == 0 || delta > 3) {
     52             unsafe = true;
     53             break;
     54           }
     55         }
     56         prev = num;
     57       }
     58       if (!unsafe) {
     59         sum++;
     60       }
     61       size = 0;
     62       ln++;
     63     }
     64     i++;
     65   }
     66   return sum;
     67 }