solved part 2

master
Jeff Yates 2020-12-09 10:36:57 -05:00
parent bee31dafb9
commit b39d71d124
1 changed files with 40 additions and 0 deletions

40
day08/solution2.rb Executable file
View File

@ -0,0 +1,40 @@
#!/bin/env ruby
def run_code (instructions)
acc = 0
tracker = Array.new(instructions.length, false)
i = 0
success = false
while tracker[i] == false do
tracker[i] = true
case instructions[i][0..2]
when 'acc'
acc += instructions[i].split(' ')[1].to_i
i += 1
when 'jmp'
i += instructions[i].split(' ')[1].to_i
when 'nop'
i += 1
end
success = true if i == instructions.length
end
return success, acc, tracker
end
input = File.readlines('./input').to_ary.map(&:strip)
succ, acc, tracker = false, 0, []
input.each.with_index do |instruction, i|
mod = input.map(&:clone)
if instruction[0..2] == 'jmp'
mod[i][0..2] = 'nop'
elsif instruction[0..2] == 'nop'
mod[i][0..2] = 'jmp'
else
next
end
succ, acc, tracker = run_code(mod)
break if succ == true
end
p acc