From 21b7041172cd2c7c463e7b884dc01d5b47048b47 Mon Sep 17 00:00:00 2001 From: Christopher Arndt Date: Mon, 4 Dec 2023 11:36:45 +0100 Subject: [PATCH] Refactor solution day 04 part 1 Signed-off-by: Christopher Arndt --- day_04/solution_04a.nim | 40 ++++++++++++++++++++++++++++------------ 1 file changed, 28 insertions(+), 12 deletions(-) diff --git a/day_04/solution_04a.nim b/day_04/solution_04a.nim index 3894ee9..c97ab51 100644 --- a/day_04/solution_04a.nim +++ b/day_04/solution_04a.nim @@ -4,19 +4,35 @@ var result = 0 var fn = if paramCount() > 0: paramStr(1) else: "input_04.txt" var lines = readFile(fn).strip.splitLines -for line in lines: - var card: int - let cardspec = line.split(":", 1) - if scanf(cardspec[0].strip, "Card$s$i", card): - let play = cardspec[1].split("|")[0].strip.splitWhitespace().mapIt(it.strip).mapIt(it.parseInt).mapIt(it.int8).toSet - 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) +# ASSUMPTION: lottery numbers are < 128 +type + Card = ref object + play, pot: set[int8] +var cards: seq[Card] +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}" case fn: