From e79043f336890658bb8b8566c56c9466a9c26a17 Mon Sep 17 00:00:00 2001 From: Daylin Morgan Date: Mon, 4 Dec 2023 03:16:12 -0600 Subject: [PATCH] solution for day 4 --- solutions/day04/example.txt | 6 ++++ solutions/day04/solution.nim | 55 ++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 solutions/day04/example.txt create mode 100644 solutions/day04/solution.nim diff --git a/solutions/day04/example.txt b/solutions/day04/example.txt new file mode 100644 index 0000000..9bdb874 --- /dev/null +++ b/solutions/day04/example.txt @@ -0,0 +1,6 @@ +Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53 +Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19 +Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1 +Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83 +Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36 +Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11 diff --git a/solutions/day04/solution.nim b/solutions/day04/solution.nim new file mode 100644 index 0000000..875d786 --- /dev/null +++ b/solutions/day04/solution.nim @@ -0,0 +1,55 @@ +import std/[math, sets, sequtils, strutils] + +const example* = slurp("example.txt").strip() +const input* = slurp("input.txt").strip() + +type + Card = object + winningNums: HashSet[int] + nums: seq[int] + +iterator parseInput(input: string): Card = + for line in input.splitLines(): + var card: Card + let s = line.split(":")[1].split("|") + for num in s[0].strip().splitWhitespace(): + card.winningNums.incl parseInt(num) + for num in s[1].strip().splitWhitespace(): + card.nums.add parseInt(num) + yield card + +proc partOne*(input: string): int = + for card in parseInput(input): + var score: int + for num in card.nums: + if num in card.winningNums: + if score == 0: inc score + else: score *= 2 + result += score + + +proc partTwo*(input: string): int = + let cards = parseInput(input).toSeq() + var winners = newSeq[int](cards.len) + for i, card in cards: + var score: int + for num in card.nums: + if num in card.winningNums: + inc score + inc winners[i] + if score > 0: + let copies = winners[i] + for j in 1..score: + winners[i+j].inc copies + return winners.sum() + + +when isMainModule: + import std/unittest + suite "day 4": + test "part one": + check partOne(example) == 13 + check partOne(input) == 22674 + test "part two": + check partTwo(example) == 30 + check partTwo(input) == 5747443