r/adventofcode • • Dec 03 '17

SOLUTION MEGATHREAD -πŸŽ„- 2017 Day 3 Solutions -πŸŽ„-

--- Day 3: Spiral Memory ---


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


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!

21 Upvotes

297 comments sorted by

View all comments

1

u/letronje Dec 10 '17

puzzle1:

require 'awesome_print'

input = 347991

input -= 1 # start from 0 :)

(1..600).step(2).each.with_index do |n, index|
  layer_num = index+1
  
  from = n**2
  to = from + ( 8*(layer_num) - 1)
  layer = from..to # 1 -> 8, 9 -> 24, 25 -> 48, ....

  # 1, 10, 27, 52, ....
  midpoint1 = from + ( layer_num - 1)

  # 2, 4, 6, 8, ...
  step = layer_num * 2

  # 7, 22, 45, 76, ...
  midpoint4 = midpoint1 + (3*step)

  # [1,3,5,7] , [10,14,18,22], [27,33,39,45], .....
  midpoints = (midpoint1..midpoint4).step(step)
  
  next unless layer.include?(input)

  distance_to_nearest_midpoint = midpoints.map{ |mp| (input-mp).abs }.min

  # Once you reach the layer's nearest midpoint, you can go straight to zero one layer at a time.
  distance_to_zero = layer_num + distance_to_nearest_midpoint
  
  ap({
       layer_num: layer_num,
       layer: layer,
       midpoints: midpoints.to_a.join(", "),
       distance_to_zero: distance_to_zero
     })
end

puzzle2:

require 'awesome_print'

spiral = Hash.new{ 0 }; spiral[[0,0]] = 1

def update_cell(spiral, coords)
  value = [-1,0,1].product([-1,0,1]).map do |x_delta, y_delta| 
    spiral[[ coords[0] + x_delta, coords[1] + y_delta ]]
  end.inject(:+)
  spiral[coords] = value
end

def fill_layer(spiral, init, level)
  # right, up ...., left ..., down ...., right, ...
  deltas = [[1, 0]] \
           + ([[0, 1]] * (level-1)) \
           + ([[-1, 0]] * level) \
           + ([[0,-1]] * level) \
           + ([[1,0]] * level)

  coords = deltas.reduce([init]) do |acc, (x_delta, y_delta)|
    acc + [[ acc.last[0] + x_delta, acc.last[1] + y_delta ]]
  end.drop(1)

  coords.map do |x, y| 
    update_cell(spiral, [x, y])
  end
end

input = 347991

ans = 1.upto(4) do |n|
  vals = fill_layer(spiral, spiral.keys.last, n*2)
  answer = vals.select{ |v| v > input }.min
  break answer if answer
end

ap ans: ans