/
day22.rb
80 lines (73 loc) · 1.61 KB
/
day22.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
def run1(grid, rounds)
hash = Hash.new(false)
n = grid.length / 2
grid.each_with_index do |line, i|
line.each_char.each_with_index do |c, j|
if c == '#'
hash[[j - n, i - n]] = true
end
end
end
pos = [0, 0]
dir = 1
infections = 0
for _ in 0...rounds
if hash[pos]
hash[pos] = false
dir = (dir - 1) % 4
else
hash[pos] = true
dir = (dir + 1) % 4
infections += 1
end
pos = pos.clone()
if dir == 0
pos[0] += 1
elsif dir == 1
pos[1] -= 1
elsif dir == 2
pos[0] -= 1
else # dir == 3
pos[1] += 1
end
end
return infections
end
def run2(grid, rounds)
hash = Hash.new(0)
n = grid.length / 2
grid.each_with_index do |line, i|
line.each_char.each_with_index do |c, j|
if c == '#'
hash[[j - n, i - n]] = 2
end
end
end
pos = [0, 0]
dir = 1
infections = 0
for _ in 0...rounds
dir = (dir + 1 - hash[pos]) % 4
hash[pos] = (hash[pos] + 1) % 4
if hash[pos] == 2
infections += 1
end
pos = pos.clone()
if dir == 0
pos[0] += 1
elsif dir == 1
pos[1] -= 1
elsif dir == 2
pos[0] -= 1
else # dir == 3
pos[1] += 1
end
end
return infections
end
def main
input = $stdin.read.split()
puts run1(input, 10000)
puts run2(input, 10000000)
end
main()