r/o
1
def surrounding(map, row, col)
2
n = 0
3
(row - 1..row + 1).each do |r|
4
(col - 1..col + 1).each do |c|
5
next if r == row && c == col
6
n += 1 if r >= 0 && c >= 0 && map[r] && map[r][c] == ?@
7
end
8
end
9
n
10
end
11
12
input = File.read('4.input')
13
_input = '
14
..@@.@@@@.
15
@@@.@.@.@@
16
@@@@@.@.@@
17
@.@@@@..@.
18
@@.@@@@.@@
19
.@@@@@@@.@
20
.@.@.@.@@@
21
@.@@@.@@@@
22
.@@@@@@@@.
23
@.@.@@@.@.
24
'
25
26
map = input.strip.split("\n")
27
height = map.length
28
width = map[0].length
29
30
this_iter = 1
31
total = 0
32
while this_iter > 0
33
to_remove = []
34
map.each.with_index.each { |line, r|
35
line.each_char.with_index.each { |char, c|
36
if char == ?@ && surrounding(map, r, c) < 4
37
to_remove << [r, c]
38
end
39
}
40
}
41
this_iter = to_remove.length
42
total += this_iter
43
to_remove.each do |(r,c)|
44
map[r][c] = '.'
45
end
46
end
47
p total
48