/* aoc-c.c: Advent of Code 2022, day 1 * * 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 "plist.h" #include "debug.h" #include "pool.h" PLIST_HEAD(plist); static int calc_top_plist(int n) { int res = 0; struct plist_node *node; plist_for_each_reverse(node, &plist) { res += node->prio; if (!--n) break; } return res; } static void parse(pool_t *pool) { size_t alloc = 0; char *buf = NULL; ssize_t buflen; int total = 0; struct plist_node *node; while (1) { buflen = getline(&buf, &alloc, stdin); switch (buflen) { case 1: case -1: node = pool_get(pool); plist_node_init(node, total); plist_add(node, &plist); total = 0; if (buflen == -1) goto end; break; default: total += atoi(buf); } } end: free(buf); return; } static int usage(char *prg) { fprintf(stderr, "Usage: %s [-d debug_level] [-p part] [-i input]\n", prg); return 1; } int main(int ac, char **av) { int opt, part = 1; while ((opt = getopt(ac, av, "d:p:")) != -1) { switch (opt) { case 'd': debug_level_set(atoi(optarg)); break; case 'p': /* 1 or 2 */ part = atoi(optarg); if (part < 1 || part > 2) return usage(*av); break; default: return usage(*av); } } if (optind < ac) return usage(*av); pool_t *pool_tot = pool_create("total", 128, sizeof(struct plist_node)); parse(pool_tot); printf("%s : res=%d\n", *av, calc_top_plist(part == 1? 1: 3)); pool_destroy(pool_tot); exit(0); }