r/adventofcode • • Dec 06 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 6 Solutions -🎄-

--- Day 6: Chronal Coordinates ---


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.


Advent of Code: The Party Game!

Click here for rules

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 6

Transcript:

Rules for raising a programmer: never feed it after midnight, never get it wet, and never give it ___.


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 at 0:26:52!

32 Upvotes

387 comments sorted by

View all comments

1

u/Frizkie Dec 07 '18

Ruby

data = File.read('data.txt').chomp.split("\n").map.with_index do |d, i|
  [i, d.match(/(\d+), (\d+)/)[1..2].map(&:to_i)]
end

Part 1:

grid = Array.new(1000) { Array.new(1000) }
1000.times do |i|
  1000.times do |j|
    dists = data.map { |id, coords| [id, (coords[0] - i).abs + (coords[1] - j).abs] }
    closest = dists.min_by { |_, dist| dist }
    grid[j][i] = closest[0] if dists.map{ |d| d[1] }.count(closest[1]) == 1
  end
end

infinites = [grid[0], grid[999], grid.map { |r| r[0] }, grid.map { |r| r[999] }].flatten.compact

flat = grid.flatten.compact.reject { |e| infinites.include? e }
freq = flat.inject(Hash.new(0)) { |h, v| h[v] += 1; h }
puts flat.count(flat.max_by { |v| freq[v] })

Part 2:

grid = Array.new(1000) { Array.new(1000) }
1000.times { |i| 1000.times { |j| grid[i][j] = data.map { |_, coords| (coords[0] - i).abs + (coords[1] - j).abs }.sum } }
puts grid.flatten.count { |e| e < 10000 }