day1_2.c (1433B)
- // 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 pass = 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');
- }
- /* brute-force it rather than math it out */
- switch(line[0])
- {
- case 'L':
- for(int a = rot; a > 0; a--)
- {
- pos = pos == 0 ? 99 : pos-1;
- if(pos == 0) pass++;
- }
- break;
- case 'R':
- for(int a = rot; a > 0; a--)
- {
- pos = pos == 99 ? 0 : pos+1;
- if(pos == 0) pass++;
- }
- break;
- }
- printf("%-4s rot:%-4d pos:%-2d pass:%d\n", line, rot, pos, pass);
- }
- free(line);
- printf("Result: %d\n", pass);
- }