Refactor solution day 04 part 1

Signed-off-by: Christopher Arndt <chris@chrisarndt.de>
This commit is contained in:
Christopher Arndt 2023-12-04 11:36:45 +01:00
parent 0f7658a8e0
commit 21b7041172
1 changed files with 28 additions and 12 deletions

View File

@ -4,19 +4,35 @@ var result = 0
var fn = if paramCount() > 0: paramStr(1) else: "input_04.txt" var fn = if paramCount() > 0: paramStr(1) else: "input_04.txt"
var lines = readFile(fn).strip.splitLines var lines = readFile(fn).strip.splitLines
for line in lines: # ASSUMPTION: lottery numbers are < 128
var card: int type
let cardspec = line.split(":", 1) Card = ref object
if scanf(cardspec[0].strip, "Card$s$i", card): play, pot: set[int8]
let play = cardspec[1].split("|")[0].strip.splitWhitespace().mapIt(it.strip).mapIt(it.parseInt).mapIt(it.int8).toSet var cards: seq[Card]
let jackpot = cardspec[1].split("|")[1].strip.splitWhitespace().mapIt(it.strip).mapIt(it.parseInt).mapIt(it.int8).toSet
#echo &"Card {card}: {left}, {right} => {left * right}"
let wins = (play * jackpot).len
if wins == 1:
result += 1
elif wins > 1:
result += 2 ^ (wins - 1)
proc points(card: Card): int =
let matches = (card.play * card.pot).len
if matches == 1:
result = 1
elif matches > 1:
result = 2 ^ (matches - 1)
else:
result = 0
for line in lines:
var cardno: int
let cardspec = line.split(":", 1)
if scanf(cardspec[0].strip, "Card$s$i", cardno):
let card = new Card
card.play = cardspec[1].split("|")[0].strip.splitWhitespace().mapIt(it.strip).mapIt(it.parseInt).mapIt(it.int8).toSet
card.pot = cardspec[1].split("|")[1].strip.splitWhitespace().mapIt(it.strip).mapIt(it.parseInt).mapIt(it.int8).toSet
echo &"Card {cardno}: {card.play}, {card.pot} => {card.points}"
cards.add(card)
result += card.points
echo &"Cards processed: {cards.len}"
echo &"Result: {result}" echo &"Result: {result}"
case fn: case fn: