Day 9! Code re-use!
This commit is contained in:
parent
b48d6aaa5f
commit
ab3eec6687
3 changed files with 42 additions and 3 deletions
|
@ -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)
|
||||
|
|
|
@ -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
|
||||
|
|
37
2020/src/day9.nim
Normal file
37
2020/src/day9.nim
Normal file
|
@ -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..<nums.len:
|
||||
var mn = n
|
||||
var mx = 0
|
||||
var sum = nums[i]
|
||||
echo i, " i: ", nums[i]
|
||||
mn = min(nums[i], mn)
|
||||
mx = max(nums[i], mx)
|
||||
for j in i+1..<nums.len:
|
||||
echo j, " j: ", nums[j], " -- ", sum
|
||||
mn = min(nums[j], mn)
|
||||
mx = max(nums[j], mx)
|
||||
if sum == n: return mn+mx
|
||||
if sum > n: continue
|
||||
sum += nums[j]
|
||||
|
Loading…
Reference in a new issue