2020-12-03 11:42:18 -06:00
|
|
|
import sets, streams, input_helpers, sequtils, options
|
2020-12-02 21:33:18 -06:00
|
|
|
|
2020-12-03 11:42:18 -06:00
|
|
|
let targetSum = 2020
|
2020-12-02 21:33:18 -06:00
|
|
|
|
2020-12-03 11:42:18 -06:00
|
|
|
proc findComplement(nums: seq[int], complement = targetSum): Option[(int, int)] =
|
|
|
|
var targets = initHashSet[int]()
|
|
|
|
for n in nums:
|
|
|
|
if targets.contains(complement - n): return some(((complement - n), n))
|
|
|
|
else: targets.incl n
|
2020-12-02 21:33:18 -06:00
|
|
|
|
2020-12-03 09:54:58 -06:00
|
|
|
proc part1*(s: Stream): int =
|
2020-12-03 11:42:18 -06:00
|
|
|
let (n1, n2) = findComplement(toSeq(asInts(s))).get; n1 * n2
|
2020-12-02 21:33:18 -06:00
|
|
|
|
2020-12-03 11:42:18 -06:00
|
|
|
proc part2*(s: Stream): int =
|
|
|
|
let nums = toSeq(asInts(s))
|
2020-12-02 21:33:18 -06:00
|
|
|
for n in nums:
|
2020-12-03 11:42:18 -06:00
|
|
|
let comp = findComplement(nums, targetSum - n)
|
|
|
|
if comp.isSome:
|
|
|
|
let (n1, n2) = comp.get; return n * n1 * n2
|