Skip to content

Commit

Permalink
Multi process solution for day 5
Browse files Browse the repository at this point in the history
  • Loading branch information
gregawoods committed Dec 9, 2023
1 parent b38655e commit 2a4842e
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 11 deletions.
1 change: 1 addition & 0 deletions Rakefile
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ require 'net/http'
namespace :solve do

task :all do
ENV['SKIP_LONG_RUNNING_SOLUTIONS'] = '1'
runner = Aoc::Runner.new
(1..25).each { |i| runner.call(i) }
end
Expand Down
45 changes: 34 additions & 11 deletions lib/days/05.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,25 +52,48 @@ def part1(input)
end

def part2(input)
# Obviously forking is not the "correct" solution to this puzzle, but sometimes
# CPUs are faster than brains, and a star is a star. Maybe refactor later. 🙃

return -1 if ENV['SKIP_LONG_RUNNING_SOLUTIONS']

seeds, mappings = parse(input)
results = {}

seeds.each_slice(2) do |index, stride|
stride.times do |n|
key = index + n
next if results.key?(key)
reads = []
writes = []

seed = index + n
mappings.each do |mapping|
seed = mapping.value(seed)
seeds.each_slice(2) do |index, stride|
read, write = IO.pipe
reads << read
writes << write

fork do
# pid = Process.pid
# puts "BEGIN #{pid}: #{index} => #{stride}"
result = Float::INFINITY

stride.times do |n|
# puts "#{pid}: #{n}/#{stride} (#{(n.to_f / stride * 100).round(1)}%)" if (n % 500_000).zero?

seed = index + n
mappings.each do |mapping|
seed = mapping.value(seed)
end
result = [seed, result].min
end

results[key] = seed
Marshal.dump(result, write)
write.close

# puts "END #{pid}: #{index} => #{stride} (Result: #{result})"
end
end
Process.waitall

writes.each(&:close)
results = reads.map { |p| Marshal.load(p.read) } # rubocop:disable Security/MarshalLoad

# Passes test but is too slow for real input
results.values.min
results.min
end

end

0 comments on commit 2a4842e

Please sign in to comment.