Day 4: Printing Department

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

FAQ

you are viewing a single comment's thread
view the rest of the comments
[โ€“] 3 points 10 months ago

Nim

type
  AOCSolution[T,U] = tuple[part1: T, part2: U]
  Vec2 = tuple[x,y: int]

proc removePaper(rolls: var seq[string]): int =
  var toRemove: seq[Vec2]
  for y, line in rolls:
    for x, c in line:
      if c != '@': continue
      var adjacent = 0
      for (dx, dy) in [(-1,-1),(0,-1),(1,-1),
                       (-1, 0),       (1, 0),
                       (-1, 1),(0, 1),(1, 1)]:
        let pos: Vec2 = (x+dx, y+dy)
        if pos.x < 0 or pos.x >= rolls[0].len or
           pos.y < 0 or pos.y >= rolls.len: continue
        if rolls[pos.y][pos.x] == '@': inc adjacent

      if adjacent < 4:
        inc result
        toRemove.add (x, y)

  for (x, y) in toRemove: rolls[y][x] = '.'

proc solve(input: string): AOCSolution[int, int] =
  var rolls = input.splitLines()
  result.part1 = rolls.removePaper()
  result.part2 = result.part1
  while (let cnt = rolls.removePaper(); result.part2 += cnt; cnt) > 0:
    discard

Today was so easy, that I decided to solve it twice, just for fun. First is a 2D traversal (see above). And then I did a node graph solution in a few minutes (in repo below). Both run in ~27 ms.

It's a bit concerning, because a simple puzzle can only mean that tomorrow will be a nightmare. Good Luck everyone, we will need it.

Full solution is at Codeberg: solution.nim

  • source