From 91725fbb82a4c72cc327ae5d3dc5d3a3249d1535 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=F0=9F=90=99PiperYxzzy?= Date: Mon, 4 Dec 2023 16:35:41 +0200 Subject: [PATCH] AoC Day 4, Part 2 (Solved) --- 2023/04/code.go | 51 +++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 47 insertions(+), 4 deletions(-) diff --git a/2023/04/code.go b/2023/04/code.go index 196715b..2450a24 100644 --- a/2023/04/code.go +++ b/2023/04/code.go @@ -18,14 +18,57 @@ func main() { // 4. with: true (part2), and user input // the return value of each run is printed to stdout func run(part2 bool, input string) any { - // when you're ready to do part 2, remove this "not implemented" block + gameIdRxp := regexp.MustCompile(`Card +(?P\d+): ?(?P.*) \| ?(?P.*)`) + if part2 { - return "not implemented" + lines := strings.Split(strings.Trim(input, "\n"), "\n") + + points := make([]int, len(lines)) + for i, line := range lines { + + matches := gameIdRxp.FindStringSubmatch(line) + if len(matches) == 0 { + continue + } + + winning := strings.Split(matches[2], " ") + drawn := strings.Split(matches[3], " ") + + points[i] = 0 + for _, win := range winning { + if win == "" { + continue + } + + for _, draw := range drawn { + if win == draw { + points[i] += 1 + } + } + } + } + + copies := make([]int, len(points)) + for i := range points { + copies[i] = 1 + } + for i, p := range points { + for j := i + 1; int(j) <= int(i)+p; j++ { + if j < len(copies) { + copies[j] += copies[i] + } + } + } + + totalCards := int(0) + for _, count := range copies { + totalCards += count + } + + return totalCards } // solve part 1 here - gameIdRxp := regexp.MustCompile(`Card +(?P\d+): ?(?P.*) \| ?(?P.*)`) - sum := 0 for _, line := range strings.Split(input, "\n") {