logo

adventofcode

Code used to solve https://adventofcode.com/, one branch per year git clone https://anongit.hacktivis.me/git/adventofcode.git/
commit: 0749a939bc1e50f0c05782038fbb3dbc11979286
parent 663cfb69b719219101950155cdcb429232355ae1
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date:   Mon,  1 Dec 2025 20:24:35 +0100

day1_2: add

Diffstat:

MMakefile3+++
Aday1_2.c85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 88 insertions(+), 0 deletions(-)

diff --git a/Makefile b/Makefile @@ -7,4 +7,7 @@ CFLAGS ?= -g -Wall -Wextra .c: $(CC) -std=c11 $(CFLAGS) -o $@ $^ $(LDFLAGS) $(LDSTATIC) +all: day1 day1_2 + day1: day1.c +day1_2: day1_2.c diff --git a/day1_2.c b/day1_2.c @@ -0,0 +1,85 @@ +// 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); +}