From 9c999e9717b7e852ebe500572f0ba34b44c2f711 Mon Sep 17 00:00:00 2001 From: Bruno Raoult Date: Fri, 9 Dec 2022 16:24:13 +0100 Subject: [PATCH] 2022 day 6: C (parts 1 and 2) --- 2022/RESULTS.txt | 8 ++++++ 2022/day06/aoc-c.c | 60 +++++++++++++++++++++++++++++++++++++++++++++ 2022/day06/aoc.bash | 2 +- 3 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 2022/day06/aoc-c.c diff --git a/2022/RESULTS.txt b/2022/RESULTS.txt index 54fd0aa..d2c48ae 100644 --- a/2022/RESULTS.txt +++ b/2022/RESULTS.txt @@ -117,7 +117,15 @@ aoc.bash: res=1658 time: 0:00.06 real, 0.06 user, 0.00 sys context-switch: 1+1, page-faults: 0+266 +aoc-c: res=1658 + time: 0:00.00 real, 0.00 user, 0.00 sys + context-switch: 0+1, page-faults: 0+87 + +++++++++++++++++ part 2 aoc.bash: res=2260 time: 0:00.09 real, 0.09 user, 0.00 sys context-switch: 1+1, page-faults: 0+265 + +aoc-c: res=2260 + time: 0:00.00 real, 0.00 user, 0.00 sys + context-switch: 0+1, page-faults: 0+87 diff --git a/2022/day06/aoc-c.c b/2022/day06/aoc-c.c new file mode 100644 index 0000000..6e5f228 --- /dev/null +++ b/2022/day06/aoc-c.c @@ -0,0 +1,60 @@ +/* aoc-c.c: Advent of Code 2022, day 6 + * + * Copyright (C) 2022 Bruno Raoult ("br") + * Licensed under the GNU General Public License v3.0 or later. + * Some rights reserved. See COPYING. + * + * You should have received a copy of the GNU General Public License along with this + * program. If not, see . + * + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +#include +#include +#include + +#include "br.h" +#include "aoc.h" + +struct msg { + char *data; + size_t len; +}; + +static struct msg *parse(struct msg *msg) +{ + size_t alloc = 0; + + msg->data=NULL; + msg->len = getline(&msg->data, &alloc, stdin); + msg->data[--msg->len] = 0; + return msg; +} + +static int solve(struct msg *msg, int marklen) +{ + char *pcur = msg->data, *pnext = pcur; + int len = msg->len, lmark = 0; + + for (; pnext < msg->data + len && lmark < marklen; lmark = ++pnext - pcur) { + for (int j = 0; j < lmark; ++j) { /* compare with prev marker chars */ + if (*(pcur+j) == *pnext) { /* check new char with cur marker */ + pcur += j + 1; /* move marker to after dup char */ + goto nextchar; + } + } + nextchar: ; + } + return pnext - msg->data; +} + +int main(int ac, char **av) +{ + int part = parseargs(ac, av); + struct msg msg; + + printf("%s: res=%d\n", *av, solve(parse(&msg), part == 1? 4:14)); + free(msg.data); + exit(0); +} diff --git a/2022/day06/aoc.bash b/2022/day06/aoc.bash index f75a458..c149736 100755 --- a/2022/day06/aoc.bash +++ b/2022/day06/aoc.bash @@ -32,7 +32,7 @@ solve() { for ((j = 0; j < lcur; ++j)); do # compare with previous ones if [[ $next == "${cur:j:1}" ]]; then # duplicate cur="${cur:j+1}$next" # keep str after dup + new char - (( lcur = lcur - j )) + (( lcur -= j )) continue 2 fi done