Watch
1
0
Fork
You've already forked advent-of-code
0

refactor: 2023 Day 2

This commit is contained in:
Jeremy Kaplan 2023-12-01 21:59:24 -08:00
commit e638563afb

View file

@ -1,34 +1,49 @@
import std/strscans import std/strscans
import std/strutils import std/strutils
type Turn = object
r, g, b: int
func parseTurn(text: string): Turn =
for count in text.split(","):
let parts = count.strip.split()
case parts[1]:
of "red": (result.r = parts[0].parseInt)
of "green": (result.g = parts[0].parseInt)
of "blue": (result.b = parts[0].parseInt)
type Game = object
id: int
turns: seq[Turn]
func parseGame(line: string): Game =
var rest: string
if not scanf(line, "Game $i: $*$.", result.id, rest):
raise newException(ValueError, line)
for turn in rest.split(";"):
result.turns.add(parseTurn(turn))
type Bag = object
r, g, b: int
proc part1(): int = proc part1(): int =
let f = open("input/day02.txt") let f = open("input/day02.txt")
defer: f.close() defer: f.close()
let let bag = Bag(r: 12, g: 13, b: 14)
reds = 12
greens = 13
blues = 14
var line: string var line: string
while f.readLine(line): while f.readLine(line):
var id: int block current:
var rest: string let game = parseGame(line)
for turn in game.turns:
block game: if turn.r > bag.r: break current
if not scanf(line, "Game $i: $*$.", id, rest): if turn.g > bag.g: break current
echo "ERROR" if turn.b > bag.b: break current
continue inc result, game.id
for counts in rest.split(";"):
var r, g, b: int
for s in counts.split(","):
let parts = s.strip.split()
case parts[1]:
of "red": (if parts[0].parseInt > reds: break game)
of "green": (if parts[0].parseInt > greens: break game)
of "blue": (if parts[0].parseInt > blues: break game)
inc result, id
proc part2(): int = proc part2(): int =
let f = open("input/day02.txt") let f = open("input/day02.txt")
@ -36,25 +51,15 @@ proc part2(): int =
var line: string var line: string
while f.readLine(line): while f.readLine(line):
var id: int var bag: Bag
var rest: string
if not scanf(line, "Game $i: $*$.", id, rest): let game = parseGame(line)
echo "ERROR" for turn in game.turns:
continue bag.r = max(bag.r, turn.r)
bag.g = max(bag.g, turn.g)
bag.b = max(bag.b, turn.b)
var reds, greens, blues: int let power = bag.r * bag.g * bag.b
for counts in rest.split(";"):
var r, g, b: int
for s in counts.split(","):
let parts = s.strip.split()
case parts[1]:
of "red": (reds = max(reds, parts[0].parseInt))
of "green": (greens = max(greens, parts[0].parseInt))
of "blue": (blues = max(blues, parts[0].parseInt))
let power = reds * greens * blues
inc result, power inc result, power
echo part1() echo part1()