This commit is contained in:
Danny Hpy 2022-01-06 12:49:08 +01:00
parent 3032a7ef81
commit 95bcf430c2
Signed by: dannyhpy
GPG Key ID: 7139FBBEA22D1CEC
1 changed files with 83 additions and 0 deletions

83
2021/10/both.nim Normal file
View File

@ -0,0 +1,83 @@
import
std/strformat,
std/strutils,
std/tables
when defined(second):
import std/algorithm
import
../../adventofcode
let input = adventofcode.getInput(2021, 10)
let lines = input.splitLines()
const chunkSymbols = (
open: {
'(': ')',
'[': ']',
'{': '}',
'<': '>'
}.toTable(),
close: {
')': '(',
']': '[',
'}': '{',
'>': '<'
}.toTable()
)
when not defined(second):
const chunkScores = {
')': 3,
']': 57,
'}': 1197,
'>': 25137
}.toTable()
else:
const chunkScores = {
')': 1,
']': 2,
'}': 3,
'>': 4
}.toTable()
var score = 0
when defined(second):
var lineScores: seq[int]
for line in lines:
var chunks: seq[char]
block abortLine:
for it in line:
if chunkSymbols.open.hasKey it:
chunks.add it
if chunkSymbols.close.hasKey it:
let expectedSymbol = chunkSymbols.open[chunks[^1]]
if it == expectedSymbol:
discard chunks.pop()
else:
# Line is corrupted.
when not defined(second):
score += chunkScores[it]
break abortLine
# Complete line by closing chunks
when defined(second):
var lineScore = 0
for idx in 0 .. chunks.high():
let it = chunks[chunks.high() - idx]
let closeSym = chunkSymbols.open[it]
lineScore *= 5
lineScore += chunkScores[closeSym]
lineScores.add lineScore
when defined(second):
lineScores.sort()
score = lineScores[lineScores.len() div 2]
echo fmt"Answer: {score}"