-
Notifications
You must be signed in to change notification settings - Fork 0
/
day11.rb
84 lines (68 loc) · 1.65 KB
/
day11.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
file = File.open("input/day11.txt", "r")
lines = file.readlines
area = []
i = 0
j = 0
for line in lines
area.push(line.strip.chars)
end
def deepCopy(arr)
return arr.map{|x| x.clone}
end
def isOccupiedDirection(x, y, dirx, diry, area, maxDist)
dist = 0
while dist < maxDist
x += dirx
y += diry
if x < 0 or y < 0 or x > area.length-1 or y > area[x].length-1
break
end
if area[x][y] == "#"
return true
end
if area[x][y] == "L"
return false
end
dist += 1
end
return false
end
def adjacentOccupied(x, y, area, maxDist = 1)
cnt = 0
for i in -1..1
for j in -1..1
if i == 0 and j == 0
next
end
if isOccupiedDirection(x, y, i, j, area, maxDist)
cnt += 1
end
end
end
return cnt
end
def run(area, maxDist, maxOccup)
seatsOcc = 0
while true
area_copy = deepCopy(area)
for i in 0..area_copy.length-1
for j in 0..area_copy[i].length-1
sp = area[i][j]
if sp == "L" and adjacentOccupied(i, j, area, maxDist) == 0
area_copy[i][j] = "#"
elsif sp == "#" and adjacentOccupied(i, j, area, maxDist) >= maxOccup
area_copy[i][j] = "L"
end
end
end
sc = area_copy.map{|line| line.count("#")}.sum
if sc == seatsOcc
break
end
seatsOcc = sc
area = deepCopy(area_copy)
end
puts seatsOcc
end
run(area, 1, 4) # part 1
run(area, 9999, 5) # part 2