44 lines
1.4 KiB
Nim
44 lines
1.4 KiB
Nim
import std/[strutils, sugar, options]
|
|
|
|
let priorityReference = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
|
|
const input = readFile("day_03/input.txt")
|
|
|
|
proc priority(c: char): int {.inline.} =
|
|
priorityReference.find(c) + 1
|
|
|
|
proc first[T](s: openArray[T], test: T -> bool): Option[T] =
|
|
for item in s:
|
|
if item.test:
|
|
return some(item)
|
|
return none[T]()
|
|
|
|
iterator groups(s: string): seq[string] =
|
|
let lines = s.splitLines()
|
|
var i = 0
|
|
while i < lines.len:
|
|
yield lines[i..i+2]
|
|
i += 3
|
|
|
|
# Find the item type that appears in both compartments of each rucksack.
|
|
# What is the sum of the priorities of those item types?
|
|
proc solvePart1() =
|
|
var sum = 0
|
|
for runsack in input.splitLines:
|
|
let compartment1 = runsack.substr(0, int(runsack.len / 2) - 1)
|
|
let compartment2 = runsack.substr(int(runsack.len / 2), runsack.len - 1)
|
|
sum += compartment1.first(c => compartment2.contains(c)).map(c => c.priority).get(0)
|
|
echo "Sum of misaligned items: " & $sum
|
|
|
|
# Find the item type that corresponds to the badges of each three-Elf group.
|
|
# What is the sum of the priorities of those item types?
|
|
proc solvePart2() =
|
|
var sum = 0
|
|
for group in groups(input):
|
|
sum += group[0].first(c => group[1].contains(c) and group[2].contains(c)).map(c => c.priority).get(0)
|
|
echo "Sum of group badges: " & $sum
|
|
|
|
if isMainModule:
|
|
solvePart1()
|
|
solvePart2()
|