mirror of
https://github.com/daylinmorgan/advent-of-code-2023.git
synced 2024-12-21 19:10:43 -06:00
solution for day 4
This commit is contained in:
parent
83c5d029aa
commit
e79043f336
2 changed files with 61 additions and 0 deletions
6
solutions/day04/example.txt
Normal file
6
solutions/day04/example.txt
Normal file
|
@ -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
|
55
solutions/day04/solution.nim
Normal file
55
solutions/day04/solution.nim
Normal file
|
@ -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
|
Loading…
Reference in a new issue