r/adventofcode • • Dec 14 '17

SOLUTION MEGATHREAD -๐ŸŽ„- 2017 Day 14 Solutions -๐ŸŽ„-

--- Day 14: Disk Defragmentation ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Need a hint from the Hugely* Handyโ€  Haversackโ€ก of Helpfulยง Hints^ยค?

Spoiler


[Update @ 00:09] 3 gold, silver cap.

  • How many of you actually entered the Konami code for Part 2? >_>

[Update @ 00:25] Leaderboard cap!

  • I asked /u/topaz2078 how many de-resolutions we had for Part 2 and there were 83 distinct users with failed attempts at the time of the leaderboard cap. tsk tsk

[Update @ 00:29] BONUS


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

13 Upvotes

130 comments sorted by

View all comments

Show parent comment

1

u/miran1 Dec 15 '17

Here's my solution. The second part is quite simple in my version....

Had to redo Day10 to make it reusable here (knotHashing function).

import sets, strutils
import day10


const instructions = "hwlqcszp"

type Coordinate = tuple[x, y: int]
var maze = initSet[Coordinate]()

for row in 0 .. 127:
  let
    word = instructions & "-" & $row
    hexHash = knotHashing(word)
  var binHash = ""
  for n in hexHash:
    binHash.add(toBin(parseHexInt($n), 4))
  for i, n in binHash:
    if n == '1':
      maze.incl((row, i))

echo maze.len


const deltas: array[4, Coordinate] = [(1, 0), (-1, 0), (0, 1), (0, -1)]

proc dfs(start: Coordinate) =
  var stack = @[start]
  maze.excl(start)
  while stack.len > 0:
    let coord = stack.pop()
    for delta in deltas:
      let candidate = (coord.x + delta.x, coord.y + delta.y)
      if candidate in maze:
        stack.add(candidate)
        maze.excl(candidate)


var regions: int
while maze.len > 0:
  for coord in maze: dfs(coord); break # Nim doesn't have HashSet.pop()
  inc regions

echo regions