day1.c (1349B)
- // SPDX-FileCopyrightText: 2025 Haelwenn (lanodan) Monnier
- // SPDX-License-Identifier: BSD-3-Clause
- #define _POSIX_C_SOURCE 202405L
- #include <stdlib.h>
- #include <stdio.h>
- #include <errno.h>
- int
- main(void)
- {
- int pos = 50; // The dial starts by pointing at 50
- int password = 0;
- char *line = NULL;
- size_t linez = 0;
- while(1)
- {
- errno = 0;
- ssize_t nread = getline(&line, &linez, stdin);
- if(nread < 0)
- {
- if(errno != 0)
- {
- perror("getline");
- free(line);
- return 1;
- }
- break;
- }
- if(line[nread-1] == '\n')
- line[nread-1] = '\0';
- if(line[0] != 'L' && line[0] != 'R')
- {
- fprintf(stderr, "Got %c instead of [LR]\n", line[0]);
- free(line);
- return 1;
- }
- if(line[1] < '0' || line[1] > '9')
- {
- fprintf(stderr, "Got %c instead of [0-9] as first digit\n", line[0]);
- free(line);
- return 1;
- }
- int rot = line[1] - '0';
- for(int i = 2; i < nread; i++)
- {
- if(line[i] < '0' || line[i] > '9') break;
- rot = (rot*10) + (line[i] - '0');
- }
- switch(line[0])
- {
- case 'L':
- pos -= rot;
- break;
- case 'R':
- pos += rot;
- break;
- }
- /* Sadly modulo doesn't works for negative inputs */
- while(pos < 0) pos += 100;
- while(pos > 99) pos -= 100;
- printf("%-4s rot:%-4d pos:%d\n", line, rot, pos);
- if(pos == 0) password++;
- }
- free(line);
- printf("Result: %d\n", password);
- }