aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNat Lasseter <user@4574.co.uk>2019-12-05 11:40:05 +0000
committerNat Lasseter <user@4574.co.uk>2019-12-05 11:40:05 +0000
commite88f1129a40134fb60a2e90b495327f6ccada871 (patch)
tree9cfdf4c6d63ff16d89aa625767189b363c6d9413
parent5e8b0fe13c85e66fa5a1f90ee13e9ddfadae5c09 (diff)
Rebuilt day02 part1 using the new scalable machine design
-rwxr-xr-xday02/part166
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)