adventofcode-2023/day_02/solution_02b.nim

48 lines
1.3 KiB
Nim
Raw Permalink Normal View History

import std/[strscans, strformat, strutils]
type
Reveal = tuple[red: int, green: int, blue: int]
Game = object
number: int
reveals: seq[Reveal]
max_red, max_green, max_blue: int
var games: seq[Game]
for line in readFile("input_02.txt").splitLines:
if line.strip.len == 0:
continue
var gameNum: int
var gamespec = line.strip.split(":", 1)
if not scanf(gamespec[0], "Game $i", gameNum):
echo "invalid line. Game number prefix mising."
var game = Game(number: gameNum)
for revealspec in gamespec[1].split(";"):
var reveal: Reveal
for dice in revealspec.strip.split(","):
var spec = dice.strip.split(" ", 1)
case spec[1].strip:
of "red":
reveal.red = parseInt(spec[0])
game.max_red = max(game.max_red, reveal.red)
of "green":
reveal.green = parseInt(spec[0])
game.max_green = max(game.max_green, reveal.green)
of "blue":
reveal.blue = parseInt(spec[0])
game.max_blue = max(game.max_blue, reveal.blue)
game.reveals.add(reveal)
games.add(game)
var result = 0
for game in games:
result += game.max_red * game.max_green * game.max_blue
echo &"Result: {result}"