2020-12-03 09:57:12 -06:00
|
|
|
import sets, streams, strutils, input_helpers
|
2020-12-02 21:33:18 -06:00
|
|
|
|
|
|
|
# Day 1
|
|
|
|
|
|
|
|
let day1TargetSum = 2020
|
|
|
|
|
2020-12-03 09:54:58 -06:00
|
|
|
proc part1*(s: Stream): int =
|
2020-12-02 21:33:18 -06:00
|
|
|
var targets = initHashSet[int]()
|
2020-12-03 09:54:58 -06:00
|
|
|
for n in asInts(s):
|
2020-12-02 21:33:18 -06:00
|
|
|
if targets.contains(day1TargetSum - n):
|
2020-12-03 09:54:58 -06:00
|
|
|
return (day1TargetSum - n) * n
|
2020-12-02 21:33:18 -06:00
|
|
|
else:
|
|
|
|
targets.incl n
|
|
|
|
|
2020-12-03 09:54:58 -06:00
|
|
|
proc part2*(strm: Stream): int =
|
2020-12-02 21:33:18 -06:00
|
|
|
# this works exactly the same as the previous algorithm, except we simply
|
|
|
|
# permute once more
|
|
|
|
# TODO: if I was really cool, I could split the shared functionality into
|
|
|
|
# a shared proc
|
|
|
|
var nums: seq[int]
|
|
|
|
for line in strm.lines():
|
|
|
|
nums.add parseInt line
|
|
|
|
for n in nums:
|
|
|
|
var iset = initHashSet[int]()
|
|
|
|
let nTargetSum = day1TargetSum - n
|
|
|
|
for n2 in nums:
|
|
|
|
if iset.contains(nTargetSum - n2):
|
2020-12-03 09:54:58 -06:00
|
|
|
return n * n2 * (nTargetSum - n2)
|
2020-12-02 21:33:18 -06:00
|
|
|
iset.incl n2
|