From 6269dd0d419e27a0457efea260490568d626c1b5 Mon Sep 17 00:00:00 2001 From: Nat Lasseter Date: Thu, 5 Dec 2019 13:50:32 +0000 Subject: Updated day02 part2 to use new machine --- day02/part2 | 64 +++++++++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 43 insertions(+), 21 deletions(-) diff --git a/day02/part2 b/day02/part2 index aadb860..20bbc66 100755 --- a/day02/part2 +++ b/day02/part2 @@ -1,40 +1,62 @@ #!/usr/bin/env ruby -Input = $stdin.readlines[0].strip.split(",").map(&:to_i) +class Machine + def initialize(starting_memory = []) + @mem = starting_memory + @pc = 0 + @halt = false + end -noun = 0 -verb = 0 + def mem(start = 0, len = @mem.length) + @mem[start...(start + len)] + end -loop do - $input = Input.dup - $input[1] = noun - $input[2] = verb + def halt! + @halt = true + end - $pc = 0 + def halt? + @halt + end - def handle_code - case $input[$pc] + def step + return if halt? + case @mem[@pc] when 1 - $input[$input[$pc+3]] = $input[$input[$pc+1]] + $input[$input[$pc+2]] - return true + @mem[@mem[@pc+3]] = @mem[@mem[@pc+1]] + @mem[@mem[@pc+2]] + @pc += 4 when 2 - $input[$input[$pc+3]] = $input[$input[$pc+1]] * $input[$input[$pc+2]] - return true + @mem[@mem[@pc+3]] = @mem[@mem[@pc+1]] * @mem[@mem[@pc+2]] + @pc += 4 when 99 - return false + halt! + @pc += 1 end end - loop do - continue = handle_code - break unless continue - $pc += 4 + def run + until halt? do + step + end end +end + +Input = $stdin.readlines[0].strip.split(",").map(&:to_i) + +noun = 0 +verb = 0 + +loop do + input = Input.dup + input[1] = noun + input[2] = verb + m = Machine.new(input) + m.run - break if $input[0] == 19690720 + break if m.mem(0, 1)[0] == 19690720 verb += 1 - if verb == 100 + if verb == 100 then verb = 0 noun += 1 end -- cgit v1.2.1