diff options
Diffstat (limited to 'day02/part1')
-rwxr-xr-x | day02/part1 | 66 |
1 files 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) |