From ab3eec6687e34e4473f720434d7de9c544f9fb5d Mon Sep 17 00:00:00 2001 From: Daniel Flanagan Date: Wed, 9 Dec 2020 09:37:54 -0600 Subject: [PATCH] Day 9! Code re-use! --- 2020/src/aoc2020.nim | 5 +++-- 2020/src/day1.nim | 3 ++- 2020/src/day9.nim | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 3 deletions(-) create mode 100644 2020/src/day9.nim diff --git a/2020/src/aoc2020.nim b/2020/src/aoc2020.nim index 9a16381..2f29270 100644 --- a/2020/src/aoc2020.nim +++ b/2020/src/aoc2020.nim @@ -8,5 +8,6 @@ proc solve_for_day(n: int) {.used.} = echo solvers[n]() when isMainModule: - solve_all() - # solve_for_day(8) + # solve_all() + # solve_for_day(1) + solve_for_day(9) diff --git a/2020/src/day1.nim b/2020/src/day1.nim index 00a880d..1fa970f 100644 --- a/2020/src/day1.nim +++ b/2020/src/day1.nim @@ -2,8 +2,9 @@ import sets, streams, input_helpers, sequtils, options let targetSum = 2020 -proc findComplement(nums: seq[int], complement = targetSum): Option[(int, int)] = +proc findComplement*(nums: openArray[int], complement = targetSum): Option[(int, int)] = var targets = initHashSet[int]() + echo nums for n in nums: if targets.contains(complement - n): return some(((complement - n), n)) else: targets.incl n diff --git a/2020/src/day9.nim b/2020/src/day9.nim new file mode 100644 index 0000000..a8f71cd --- /dev/null +++ b/2020/src/day9.nim @@ -0,0 +1,37 @@ +import streams, sequtils, sets, options, deques, input_helpers, day1 + +const WINDOW = 25 + +proc part1*(s: Stream): int = + var rollingWindow = initDeque[int](WINDOW) + for i in s.asInts: + echo i + if rollingWindow.len < WINDOW: + rollingWindow.addFirst(i) + continue + else: + let maybe = toSeq(rollingWindow).findComplement(i) + if maybe.isSome: + rollingWindow.addFirst(i) + rollingWindow.popLast + else: return i + +proc part2*(s: Stream): int = + let n = s.part1 + s.setPosition 0 + let nums = toSeq(s.asInts) + for i in 0.. n: continue + sum += nums[j] +