Created
December 19, 2017 15:29
-
-
Save kejadlen/836765df6e4475681627738fd7e180c0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Program | |
| def initialize(id, instructions, input, output) | |
| @id, @instructions, @input, @output = id, instructions, input, output | |
| @registers = Hash.new {|h,k| | |
| if k =~ /[a-z]/ | |
| h[k] = 0 | |
| else | |
| h[k] = k.to_i | |
| end | |
| } | |
| @registers["p"] = id | |
| @pc = 0 | |
| @sent = 0 | |
| end | |
| def run | |
| while instruction = @instructions[@pc] | |
| case instruction | |
| when /snd (\w)/ | |
| @output << @registers[$1] | |
| p "#{@id} -> #{@registers[$1]}" | |
| @sent += 1 | |
| p @sent if @id == 1 | |
| @pc += 1 | |
| when /set (\w) (.+)/ | |
| @registers[$1] = @registers[$2] | |
| @pc += 1 | |
| when /add (\w) (.+)/ | |
| @registers[$1] += @registers[$2] | |
| @pc += 1 | |
| when /mul (\w) (.+)/ | |
| @registers[$1] *= @registers[$2] | |
| @pc += 1 | |
| when /mod (\w) (.+)/ | |
| @registers[$1] %= @registers[$2] | |
| @pc += 1 | |
| when /rcv (\w)/ | |
| until value = @input.shift | |
| Thread.pass | |
| end | |
| p "#{@id} <- #{value}" | |
| @registers[$1] = value | |
| @pc += 1 | |
| when /jgz (\w) (.+)/ | |
| @pc += if @registers[$1].zero? | |
| 1 | |
| else | |
| @registers[$2] | |
| end | |
| else | |
| raise instruction | |
| end | |
| end | |
| end | |
| end | |
| instructions = ARGF.read.strip.lines | |
| instructions = <<EOF.strip.lines | |
| snd 1 | |
| snd 2 | |
| snd p | |
| rcv a | |
| rcv b | |
| rcv c | |
| rcv d | |
| EOF | |
| queue_0 = [] | |
| queue_1 = [] | |
| program_0 = Program.new(0, instructions, queue_1, queue_0) | |
| program_1 = Program.new(1, instructions, queue_0, queue_1) | |
| threads = [] | |
| threads << Thread.new { program_0.run } | |
| threads << Thread.new { program_1.run } | |
| threads.each do |thread| | |
| thread.join | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment