From 73ca0bca600c77b8821ff4924c2099bdaad8d6a9 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Mon, 7 Dec 2020 21:20:06 -0800 Subject: [PATCH] [2020][ruby][8.x] --- 2020/ruby/day_08.rb | 55 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 2020/ruby/day_08.rb diff --git a/2020/ruby/day_08.rb b/2020/ruby/day_08.rb new file mode 100644 index 0000000..494ac94 --- /dev/null +++ b/2020/ruby/day_08.rb @@ -0,0 +1,55 @@ +require "set" + +class Program + attr_reader :accumulator + + def initialize(instructions) + @instructions = instructions + @accumulator = 0 + @pc = 0 + end + + def run + seen = Set.new + + loop do + break if @pc == @instructions.size + + fail if seen.include?(@pc) + seen << @pc + + op, arg = @instructions.fetch(@pc) + case op + when :acc + @accumulator += arg + @pc += 1 + when :jmp + @pc += arg + when :nop + @pc += 1 + else + fail + end + end + end +end + +instructions = ARGF.read.scan(/(\w+) ([-+]\d+)/).map {|op,arg| [op.to_sym, arg.to_i] } +uncorrupt = { nop: :jmp, jmp: :nop } +(0...instructions.size).select {|i| + op, _ = instructions.fetch(i) + uncorrupt.has_key?(op) +}.map {|i| + attempt = instructions.clone + instruction = attempt.fetch(i) + attempt[i] = [uncorrupt.fetch(instruction[0]), instruction[1]] + attempt +}.each do |i| + program = Program.new(i) + begin + program.run + rescue + next + end + puts "accumulator: #{program.accumulator}" +end