euler/ruby/euler018.rb

108 lines
2.6 KiB
Ruby
Raw Normal View History

2014-04-25 23:59:14 +00:00
triangle = [[75],
[95,64],
[17,47,82],
[18,35,87,10],
[20, 4,82,47,65],
[19, 1,23,75, 3,34],
[88, 2,77,73, 7,63,67],
[99,65, 4,28, 6,16,70,92],
[41,41,26,56,83,40,80,70,33],
[41,48,72,33,47,32,37,16,94,29],
[53,71,44,65,25,43,91,52,97,51,14],
[70,11,33,28,77,73,17,78,39,68,17,57],
[91,71,52,38,17,14,91,43,58,50,27,29,28],
[63,66, 4,68,89,53,67,30,73,16,69,87,40,31],
[ 4,62,98,27,23, 9,70,98,73,93,38,53,60, 4,23]]
class Triangle
def initialize(list_of_lists)
@data = list_of_lists
@route_length = {}
locations.each do |location|
@route_length[location] = @data[location.first][location.last]
end
end
def locations
locations = []
(0..row_count-1).each do |row_num|
(0..row_num).each do |index|
locations << [row_num, index]
end
end
locations
end
def row(num)
@data[num]
end
def row_count
@data.count
end
def route_length(row, index_from_left)
@route_length[[row, index_from_left]]
end
def root
@data.first.first
end
def element(row_num, index_from_left)
row(row_num)[index_from_left]
end
def children_of_element(row_num, index_from_left)
unless is_bottom_row?(row_num)
[@route_length[[row_num+1, index_from_left]], @route_length[[row_num+1, index_from_left+1]]]
else
[]
end
end
def is_bottom_row?(row_num)
row_num == @data.count - 1
end
def bottom_row
@data.count - 1
end
def maximum_route_total
((bottom_row-1).downto(0)).each do |row_num|
(0..@data[row_num].length-1).each do |index|
children = children_of_element(row_num, index)
current_elt = element(row_num, index)
choose_first_elt = current_elt + children.first
choose_second_elt = current_elt + children.last
@route_length[[row_num, index]] = [choose_first_elt, choose_second_elt].max
end
end
@route_length[[0,0]]
end
end
def parse_triangle(filename)
triangle_data = []
File.open(filename, 'r') do |file|
while line = file.gets
triangle_data << line.split(" ").map(&:to_i)
end
end
Triangle.new(triangle_data)
end
parsed_triangle = parse_triangle("triangle18.txt")
triangle_two = Triangle.new([ [3],
[7,4],
[2,4,6],
[8,5,9,3] ])
triangle_67 = parse_triangle("triangle67.txt")
puts triangle_two.maximum_route_total.inspect
puts parsed_triangle.maximum_route_total.inspect
puts triangle_67.maximum_route_total.inspect