-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path10b.rb
53 lines (40 loc) · 1.23 KB
/
10b.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
require 'set'
def parse_input
map = {}
peaks = Set.new
trailheads = Set.new
input = File.readlines('inputs/10', chomp: true)
rows = input.length
cols = input[0].length
input.each_with_index do |line, row|
line.strip.chars.each_with_index do |char, col|
height = char.to_i
map[[row,col]] = height
peaks << [row,col] if height == 9
trailheads << [row,col] if height == 0
end
end
[map, rows, cols, peaks, trailheads]
end
def out_of_bounds?(row, col, rows, cols)
row < 0 || row >= rows || col < 0 || col >= cols
end
def solve
map, rows, cols, peaks, trailheads = parse_input
solution = Hash.new { |hash, key| hash[key] = 0 }
traverse = ->(row, col, prev_value) do
return if out_of_bounds?(row, col, rows, cols)
if map[[row,col]] == prev_value - 1
solution[[row,col]] += 1
traverse.call(row - 1, col, prev_value - 1)
traverse.call(row + 1, col, prev_value - 1)
traverse.call(row, col + 1, prev_value - 1)
traverse.call(row, col - 1, prev_value - 1)
end
end
# Call traverse for each peak
peaks.each { |pos| traverse.call(*pos, 9 + 1) }
# Sum the amount of ways to get to the peak
trailheads.sum { |trailhead| solution[trailhead] }
end
puts solve