From e88f1129a40134fb60a2e90b495327f6ccada871 Mon Sep 17 00:00:00 2001 From: Nat Lasseter Date: Thu, 5 Dec 2019 11:40:05 +0000 Subject: Rebuilt day02 part1 using the new scalable machine design --- day02/part1 | 66 +++++++++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 45 insertions(+), 21 deletions(-) diff --git a/day02/part1 b/day02/part1 index 460b3b5..da8226b 100755 --- a/day02/part1 +++ b/day02/part1 @@ -1,28 +1,52 @@ #!/usr/bin/env ruby -$input = $stdin.readlines[0].strip.split(",").map(&:to_i) -$pc = 0 - -def handle_code - case $input[$pc] - when 1 - $input[$input[$pc+3]] = $input[$input[$pc+1]] + $input[$input[$pc+2]] - return true - when 2 - $input[$input[$pc+3]] = $input[$input[$pc+1]] * $input[$input[$pc+2]] - return true - when 99 - return false +class Machine + def initialize(starting_memory = []) + @mem = starting_memory + @pc = 0 + @halt = false + end + + def mem(start = 0, len = @mem.length) + @mem[start...(start + len)] + end + + def halt! + @halt = true + end + + def halt? + @halt end -end -$input[1] = 12 -$input[2] = 2 + def step + return if halt? + case @mem[@pc] + when 1 + @mem[@mem[@pc+3]] = @mem[@mem[@pc+1]] + @mem[@mem[@pc+2]] + @pc += 4 + when 2 + @mem[@mem[@pc+3]] = @mem[@mem[@pc+1]] * @mem[@mem[@pc+2]] + @pc += 4 + when 99 + halt! + @pc += 1 + end + end -loop do - continue = handle_code - break unless continue - $pc += 4 + def run + until halt? do + step + end + end end -puts $input[0] +input = $stdin.readlines[0].strip.split(",").map(&:to_i) + +input[1] = 12 +input[2] = 2 + +m = Machine.new(input) +m.run + +puts m.mem(0, 1) -- cgit v1.2.1