From 526f8216e3813f6b7cd59aea91e9d2ceae2a3e5e Mon Sep 17 00:00:00 2001 From: Alexander Avery Date: Tue, 5 Dec 2023 11:49:24 -0500 Subject: [PATCH] complete day 4 part 2 --- day04.go | 40 +++++++++++++++++++++++++++++----------- 1 file changed, 29 insertions(+), 11 deletions(-) diff --git a/day04.go b/day04.go index 0f8b873..6506e94 100644 --- a/day04.go +++ b/day04.go @@ -69,24 +69,42 @@ func (d day04) solve1(r io.Reader) string { return fmt.Sprintf("%d", sum) } +func expand(cursor, matches int, duplicates []int) []int { + if cursor+matches > len(duplicates) { + tmp := make([]int, cursor+matches) + for i := range duplicates { + tmp[i] = duplicates[i] + } + duplicates = tmp + } + + for i := cursor; i < cursor+matches; i++ { + duplicates[i] = duplicates[i] + 1 + + // only count duplicates if we are past the first card + if cursor > 0 { + duplicates[i] = duplicates[i] + duplicates[cursor-1] + } + } + + return duplicates +} + func (d day04) solve2(r io.Reader) string { var ( - current int - sum = 1 - cards = make([]int, 185) - scanner = bufio.NewScanner(r) + cursor int + duplicates = make([]int, 0) + scanner = bufio.NewScanner(r) ) - for matches := -1; scanner.Scan() && matches != 0; current++ { + for matches := -1; scanner.Scan() && matches != 0; cursor++ { _, line, _ := strings.Cut(scanner.Text(), ": ") - sum++ - matches = countwinings(line) - for i := 1; i <= matches; i++ { - cards[current+i] = cards[current+i] + 1 + cards[current] - } + matches := countwinings(line) + duplicates = expand(cursor, matches, duplicates) } - for _, c := range cards { + sum := cursor + for _, c := range duplicates { sum += c } return fmt.Sprintf("%d", sum)