From a28f8de0b2b0c4216e2c191113ffdcd35eb7a526 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Sat, 7 Dec 2019 10:05:36 -0800 Subject: [PATCH] [2019][ruby][7.b] --- 2019/ruby/day_07.rb | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/2019/ruby/day_07.rb b/2019/ruby/day_07.rb index df56b57..2773a35 100644 --- a/2019/ruby/day_07.rb +++ b/2019/ruby/day_07.rb @@ -2,11 +2,26 @@ require_relative "computer" program = ARGF.read -puts (0..4).to_a.permutation.map {|phase_settings| +p (5..9).to_a.permutation.map {|phase_settings| amplifiers = Array.new(5) { Computer.from(program) } - amplifiers.zip(phase_settings).inject(?0) {|i, (a, ps)| - output = StringIO.new - a.run(StringIO.new("#{ps}\n#{i}"), output) - output.string - }.to_i + + pipes = Array.new(5) { IO.pipe } + + # input phase settings + pipes.zip(phase_settings).each do |(_, w), ps| + w.puts(ps) + end + + # first 0 signal + pipes.first.last.puts(?0) + + ios = pipes.cycle.each_cons(2).take(5).map {|(r, _), (_, w)| [r, w] } + + ts = amplifiers.zip(ios).map {|(a, (i, o))| + Thread.new { a.run(i, o) } + } + ts.each(&:join) + + thrusters_input = ios.first.first + thrusters_input.gets.to_i }.max