-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathd14.rb
123 lines (112 loc) · 2.23 KB
/
d14.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
def north_support_load(map)
load = 0
rows = map.length
cols = map[0].length
(0...rows).each do |row|
(0...cols).each do |col|
load += rows - row if map[row][col] == 'O'
end
end
load
end
def tilt_north(map)
rows = map.length
cols = map[0].length
(0...cols).each do |col|
top_row = 0
(0...rows).each do |row|
case map[row][col]
when '#'
top_row = row + 1
when 'O'
map[row][col] = '.'
map[top_row][col] = 'O'
top_row += 1
end
end
end
end
def tilt_south(map)
rows = map.length
cols = map[0].length
(0...cols).each do |col|
bottom_row = rows - 1
(0...rows).reverse_each do |row|
case map[row][col]
when '#'
bottom_row = row - 1
when 'O'
map[row][col] = '.'
map[bottom_row][col] = 'O'
bottom_row -= 1
end
end
end
end
def tilt_west(map)
rows = map.length
cols = map[0].length
(0...rows).each do |row|
left_col = 0
(0...cols).each do |col|
case map[row][col]
when '#'
left_col = col + 1
when 'O'
map[row][col] = '.'
map[row][left_col] = 'O'
left_col += 1
end
end
end
end
def tilt_east(map)
rows = map.length
cols = map[0].length
(0...rows).each do |row|
right_col = cols - 1
(0...cols).reverse_each do |col|
case map[row][col]
when '#'
right_col = col - 1
when 'O'
map[row][col] = '.'
map[row][right_col] = 'O'
right_col -= 1
end
end
end
end
def cycle(map)
tilt_north(map)
tilt_west(map)
tilt_south(map)
tilt_east(map)
end
def solve(file_name)
map = File.open(file_name, 'r').readlines(chomp: true).map(&:chars)
tilt_north(map.dup)
puts("Part1: #{north_support_load(map)}")
history = {}
loads = {}
n = 0
loop do
n += 1
cycle(map)
load = north_support_load(map)
hash = map.hash
prev_n = history[hash]
if prev_n
cycle_length = n - prev_n
result = loads[prev_n + ((1_000_000_000 - prev_n) % cycle_length)]
puts("Part2: #{result}")
break
end
history[hash] = n
loads[n] = load
end
end
puts('== TEST ==')
solve('test/d14.txt')
puts('== INPUT ==')
solve('input/d14.txt')