-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path11-2.rb
executable file
·109 lines (93 loc) · 1.95 KB
/
11-2.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
102
103
104
105
106
107
108
109
#!/usr/bin/env ruby
require 'numo/narray'
class Map
attr_accessor :num_flashes
def initialize(input)
@size = 10
@map = Numo::UInt8.zeros(@size, @size)
input.each_index do |row|
input[row].each_index do |col|
@map[row, col] = input[row][col]
end
end
@flashed = Numo::UInt8.zeros(@size, @size)
@num_flashes = 0
end
def increase(row, col)
return unless row.between?(0, @size - 1)
return unless col.between?(0, @size - 1)
@map[row, col] += 1
end
def energize
@size.times do |row|
@size.times do |col|
increase(row, col)
end
end
end
def flash
flashed = false
@size.times do |row|
@size.times do |col|
next unless @map[row, col] > 9 and
@flashed[row, col].zero?
@num_flashes += 1
flashed = true
@flashed[row, col] = 1
increase(row - 1, col - 1)
increase(row - 1, col)
increase(row - 1, col + 1)
increase(row, col - 1)
increase(row, col + 1)
increase(row + 1, col - 1)
increase(row + 1, col)
increase(row + 1, col + 1)
end
end
flashed
end
def reset
@size.times do |row|
@size.times do |col|
@map[row, col] = 0 if @flashed[row, col] == 1
end
end
@flashed.fill 0
end
def step
energize
loop do
break unless flash
end
all_flashed = true
@size.times do |row|
@size.times do |col|
all_flashed = false if @flashed[row, col].zero?
end
end
reset
all_flashed
end
def to_s
s = "<#{self.class}:\n"
@size.times do |row|
@size.times do |col|
s += "#{@map[row, col]} "
end
s += "\n"
end
s += '>'
s
end
def inspect
to_s
end
end
input = File.read('11.input').lines.map(&:strip).map { |row| (row.split '').map &:to_i }
map = Map.new(input)
step = 0
loop do
step += 1
break if map.step
end
print step, "\n"