advent-of-code-2023/solutions/day02/solution.nim

60 lines
1.5 KiB
Nim
Raw Normal View History

2023-12-02 12:06:32 -06:00
import std/[strutils, strscans]
2023-12-02 11:25:11 -06:00
const example* = slurp("example.txt").strip()
const input* = slurp("input.txt").strip()
2023-12-02 12:06:32 -06:00
type
Color {.pure.} = enum
red, blue, green
2023-12-02 11:25:11 -06:00
2023-12-02 12:06:32 -06:00
Cubes = array[Color, int]
2023-12-02 11:25:11 -06:00
Game = object
2023-12-02 12:06:32 -06:00
turns: seq[Cubes]
2023-12-02 11:25:11 -06:00
proc parseInput(input: string): seq[Game] =
for line in input.splitLines:
result.add Game()
let turns = line.split(":")[1]
for turn in turns.split(";"):
2023-12-02 12:06:32 -06:00
var cubes: Cubes
for cubeStr in turn.split(","):
var cnt: int
var color: string
discard cubeStr.strip().scanf("$i $w", cnt, color)
cubes[parseEnum[Color](color)] = cnt
result[^1].turns.add cubes
proc isValid(game: Game): bool =
const limits: Cubes = [red: 12, blue: 14, green: 13]
for turn in game.turns:
for col, cnt in turn:
if cnt > limits[col]:
return false
2023-12-02 11:25:11 -06:00
return true
proc partOne*(input: string): int =
var games = parseInput(input)
for i, game in games:
2023-12-02 12:06:32 -06:00
if game.isValid():
2023-12-02 11:25:11 -06:00
result += (i+1)
proc partTwo*(input: string): int =
var games = parseInput(input)
for i, game in games:
2023-12-02 12:06:32 -06:00
var mins: Cubes
2023-12-02 11:25:11 -06:00
for turn in game.turns:
2023-12-02 12:06:32 -06:00
for col, cnt in turn:
mins[col] = max(mins[col], cnt)
result += mins[red] * mins[green] * mins[blue]
2023-12-02 11:25:11 -06:00
when isMainModule:
import std/unittest
suite "day 2":
test "part one":
check partOne(example) == 8
check partOne(input) == 2239
test "part two":
check partTwo(example) == 2286
check partTwo(input) == 83435