From a3164c03bedb620535f5450d5b1cc13093ec2144 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Sun, 1 Dec 2019 21:10:32 -0800 Subject: [PATCH] [2019][ruby][2.x] --- 2019/ruby/day_02.rb | 47 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 2019/ruby/day_02.rb diff --git a/2019/ruby/day_02.rb b/2019/ruby/day_02.rb new file mode 100644 index 0000000..35dc040 --- /dev/null +++ b/2019/ruby/day_02.rb @@ -0,0 +1,47 @@ +OPCODES = ARGF.read.split(?,).map(&:to_i) + +# opcodes[1] = 12 +# opcodes[2] = 2 + +# pc = 0 +# loop do +# p opcodes +# case opcodes[pc] +# when 1 +# opcodes[opcodes[pc+3]] = opcodes[opcodes[pc+1]] + opcodes[opcodes[pc+2]] +# pc += 4 +# when 2 +# opcodes[opcodes[pc+3]] = opcodes[opcodes[pc+1]] * opcodes[opcodes[pc+2]] +# pc += 4 +# when 99 +# puts opcodes[0] +# exit +# end +# end + +def run(noun, verb) + memory = OPCODES.dup + memory[1] = noun + memory[2] = verb + + pc = 0 + loop do + case memory[pc] + when 1 + memory[memory[pc+3]] = memory[memory[pc+1]] + memory[memory[pc+2]] + pc += 4 + when 2 + memory[memory[pc+3]] = memory[memory[pc+1]] * memory[memory[pc+2]] + pc += 4 + when 99 + return memory[0] + end + end +end + +(0..99).each do |noun| + (0..99).each do |verb| + value = run(noun, verb) + puts 100 * noun + verb and exit if value == 19690720 + end +end