project_euler/18.rb
Code:
# Project Euler Problem 18: Maximum Path Sum I
# https://projecteuler.net/problem=18
require_relative './helpers.rb'
def find(triangle, row)
triangle[row].map!.with_index do |n, i|
l = triangle[row + 1][i]
r = triangle[row + 1][i + 1]
l > r ? n.to_i + l.to_i : n.to_i + r.to_i
end
return triangle if row == 0
return find(triangle, row - 1)
end
def solve(triangle)
sum, path = find(triangle, triangle.size - 2)[0]
return sum
end
example = [['3'], ['7', '4'], ['2', '4', '6'], ['8', '5', '9', '3']]
triangle = get_dataset(problem: 18).map { |line| line.split(' ') }
puts solve(example)
puts solve(triangle)
Output:
23
1074