🏡 2020/day01.nim

--- Day 1: Report Repair ---

input

let input: seq[int] = toSeq("2020/input01.txt".lines).map(parseInt)
echo input.len
echo input[0 .. 10]
echo input[^10 .. ^1]
200
@[1583, 1295, 1747, 1628, 1756, 1992, 1984, 1990, 2006, 1626, 1292]
@[1743, 1909, 1451, 2000, 1978, 1938, 1707, 1337, 1362, 1263]

-- Part 1 --

solution to parse 1 does not necessarily even needs to parse the whole input. this solution is correct also for the edge case 2010 + 2010

var s, t: seq[int]
for n in input:
  if n < 1010:
    t.add n
  if 2020 - n in s:
    echo "part 1: ", n * (2020 - n)
  s.add n
part 1: 538464

That's the right answer! You are one gold star closer to saving your vacation.

-- Part 2 --

s.sort()
t.sort()
block outer:
  for i, n in s:
    for m in s[(i + 1) .. ^1]:
      for k in t:
        if n + m + k == 2020:
          echo "part 2: ", n * m * k
          break outer
        if n + m + k > 2020:
          break
part 2: 278783190

That's the right answer! You are one gold star closer to saving your vacation.

import nimib, animu

nbInit
nbDoc.darkMode # only to have github logo in dark mode (the rest is in custom head)
nbText : "# --- Day 1: Report Repair ---"

nbText: "## input"

nbCode:
  let input: seq[int] = toSeq("2020/input01.txt".lines).map(parseInt)
  echo input.len
  echo input[0 .. 10]
  echo input[^10 .. ^1]

nbText: "## -- Part 1 --"
nbText: """
solution to parse 1 does not necessarily even needs to parse the whole input.
this solution is correct also for the edge case 2010 + 2010"""

nbCode:
  var s, t: seq[int]  # t used in part 2
    
  for n in input:
    if n < 1010:
      t.add n
    if 2020 - n in s:
      echo "part 1: ", n*(2020 - n)
    s.add n

gotTheStar

nbText: "## -- Part 2 --"

nbCode:
  s.sort()
  t.sort()
  block outer:
    for i, n in s:
      for m in s[(i + 1) .. ^1]:
        for k in t:
          if n + m + k == 2020:
            echo "part 2: ", n*m*k
            break outer
          if n + m + k > 2020:
            break

gotTheStar

# TODO: fix how code elements look like when not a direct child of pre
# nbText: "the above solution is not necessarily correct since `k in t` could be one of `n` or `m`"

nbSave