-
Notifications
You must be signed in to change notification settings - Fork 0
/
day6.rb
101 lines (86 loc) · 2.15 KB
/
day6.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
class LightGrid
def initialize(width, height)
@array = height.times.map do
[0] * width
end
end
def total_brightness
@array.inject(0) { |sum, a| sum + a.inject(:+) }
end
def parse_instructions(i)
i.sub! 'turn ', ''
i = i.split ' '
i[1] = i[1].split(',').map(&:to_i)
i[3] = i[3].split(',').map(&:to_i)
{
action: i.first,
start: {
x: i[1].first,
y: i[1].last
},
finish: {
x: i[3].first,
y: i[3].last
}
}
end
def update!(start, finish, val=nil)
(start[:x]..finish[:x]).each do |x|
(start[:y]..finish[:y]).each do |y|
@array[x][y] = val ? val : yield(@array[x][y])
end
end
end
def toggle!(start, finish)
update!(start, finish) { |val| (val-1).abs }
end
def on!(start, finish)
update!(start, finish, 1)
end
def off!(start, finish)
update!(start, finish, 0)
end
def increase_brightness!(start, finish, amt = 1)
update!(start, finish) { |val| val + amt }
end
def decrease_brightness!(start, finish)
update!(start, finish) { |val| val == 0 ? 0 : val - 1}
end
def do(instruction_line)
ins = parse_instructions instruction_line
case ins[:action]
when 'toggle'
toggle! ins[:start], ins[:finish]
when 'on'
on! ins[:start], ins[:finish]
when 'off'
off! ins[:start], ins[:finish]
end
end
def corrected_do(instruction_line)
ins = parse_instructions instruction_line
case ins[:action]
when 'toggle'
increase_brightness! ins[:start], ins[:finish], 2
when 'on'
increase_brightness! ins[:start], ins[:finish]
when 'off'
decrease_brightness! ins[:start], ins[:finish]
end
end
def print_grid
@array.each do |a|
p a
end
end
end
lights = LightGrid.new(1000, 1000)
corrected_lights = LightGrid.new(1000, 1000)
File.open('input', 'r') do |infile|
while(line = infile.gets)
lights.do(line)
corrected_lights.corrected_do(line)
end
end
p "The total number of active lights is: #{lights.total_brightness}"
p "The total brightness of the lights after correction is: #{corrected_lights.total_brightness}"