From 536d83a552403d7e0dd7da8b073e09629ae7253e Mon Sep 17 00:00:00 2001 From: Danny Harpigny Date: Sat, 21 Jan 2023 20:41:50 +0100 Subject: [PATCH] --- 2022/02/first.nim | 43 +++++++++++++++++++++++++++++++++ 2022/02/second.nim | 60 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+) create mode 100644 2022/02/first.nim create mode 100644 2022/02/second.nim diff --git a/2022/02/first.nim b/2022/02/first.nim new file mode 100644 index 0000000..01c91e3 --- /dev/null +++ b/2022/02/first.nim @@ -0,0 +1,43 @@ +import + std/strformat, + std/strutils, + std/tables + +import + ../../adventofcode + +let input = adventofcode.getInput() + +var score = 0 + +type + Choices = enum + rock, paper, scissors + +let choices = toTable({ + 'A': rock, + 'B': paper, + 'C': scissors, + 'X': rock, + 'Y': paper, + 'Z': scissors, +}) + +for line in input.splitLines: + let opponentChoice = choices[line[0]] + let ourChoice = choices[line[2]] + + # The choice we make is added to the score + score += 1 + ord ourChoice + + let outcome = ord(ourChoice) - ord(opponentChoice) + case outcome + of -2: score += 6 + of -1: score += 0 + of 0: score += 3 + of 1: score += 6 + of 2: score += 0 + else: + raise newException(ValueError, fmt"Outcome: {outcome}") + +echo fmt"Answer: {score}" diff --git a/2022/02/second.nim b/2022/02/second.nim new file mode 100644 index 0000000..abe732f --- /dev/null +++ b/2022/02/second.nim @@ -0,0 +1,60 @@ +import + std/strformat, + std/strutils, + std/tables + +import + ../../adventofcode + +let input = adventofcode.getInput() + +var score = 0 + +type + Choice = enum + cRock = 'A', + cPaper = 'B', + cScissors = 'C' + RequiredOutcome = enum + roDefeat = 'X', + roDraw = 'Y', + roVictory = 'Z' + +let choiceScores = toTable({ + cRock: 1, + cPaper: 2, + cScissors: 3, +}) + +for line in input.splitLines: + let opponentChoice = Choice line[0] + let requiredOutcome = RequiredOutcome line[2] + var ourChoice: Choice + + case requiredOutcome + of roDefeat: + score += 0 + case opponentChoice + of cRock: + ourChoice = cScissors + of cPaper: + ourChoice = cRock + of cScissors: + ourChoice = cPaper + of roDraw: + score += 3 + ourChoice = opponentChoice + of roVictory: + score += 6 + case opponentChoice + of cRock: + ourChoice = cPaper + of cPaper: + ourChoice = cScissors + of cScissors: + ourChoice = cRock + + # The choice we make is added to the score + score += choiceScores[ourChoice] + +echo fmt"Answer: {score}"