-
Notifications
You must be signed in to change notification settings - Fork 0
/
day_02.rb
61 lines (54 loc) · 1.15 KB
/
day_02.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
program = File
.read('day-02.txt')
.strip
.split(",")
.map(&:to_i)
magic_number = 19690720
class Runner
attr_reader :program
def initialize(program)
@program = program
@pointer = 0
end
def run
loop do
case @program[@pointer]
when 1
add
when 2
multiply
when 99
break
else
raise "Invalid opcode at #{@pointer}: #{@program[@pointer]}!"
end
end
end
def add
positions = @program[(@pointer + 1)..(@pointer + 3)]
result = @program[positions[0]] + @program[positions[1]]
@program[positions[2]] = result
@pointer += 4
end
def multiply
positions = @program[(@pointer + 1)..(@pointer + 3)]
result = @program[positions[0]] * @program[positions[1]]
@program[positions[2]] = result
@pointer += 4
end
end
(0..99).each do |noun|
(0..99).each do |verb|
attempt = program.dup
attempt[1] = noun
attempt[2] = verb
runner = Runner.new(attempt)
runner.run
if runner.program[0] == magic_number
puts 'Yes!'
puts [noun, verb]
puts runner.program[0]
puts "#{((100 * noun) + verb)}"
end
end
end