-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheuler-067
22 lines (18 loc) · 814 Bytes
/
euler-067
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Read the triangle from the file and convert it to a 2D array of integers
triangle = File.readlines("triangle.txt").map do |line|
line.split.map(&:to_i)
end
# Start from the second-to-last row and move upwards
(triangle.length - 2).downto(0) do |current_row|
triangle[current_row].each_with_index do |value, index|
# Find the maximum of the two adjacent numbers in the row below
left_path = triangle[current_row + 1][index]
right_path = triangle[current_row + 1][index + 1]
max_path = [left_path, right_path].max
# Add the maximum path value to the current number
triangle[current_row][index] += max_path
end
end
# The maximum total is now at the top of the triangle
maximum_total = triangle[0][0]
puts "The maximum total from top to bottom of the triangle is: #{maximum_total}"