Skip to content

Instantly share code, notes, and snippets.

@timols
Last active December 16, 2015 06:38
Show Gist options
  • Save timols/5392588 to your computer and use it in GitHub Desktop.
Save timols/5392588 to your computer and use it in GitHub Desktop.
Given a pyramid of positive integers, calculate the min sum that can be created by traversing the pyramid and selecting either the left or right element on the next row.
#!/usr/bin/env ruby
# Construct a Pyramid structure
# from text, given the following format
#
# 1
# 1 2
# 1 2 3
# 1 2 3 4
class Pyramid
attr_reader :size
def initialize(text)
@data = text.split("\n").map do |line|
line.split(" ").map(&:to_i)
end
@size = @data.length
end
def row(i)
@data[i]
end
def min_path
sums = @data.clone # Cloning in case we choose to reuse the data
# Start from the bottom!
(@size - 2).downto(0).each do |j|
(0...row(j).length).each do |i|
sums[j][i] += [sums[j + 1][i], sums[j + 1][i + 1]].min
end
end
# The first element in the sums will be the correct solution since
# we've been progressively adding elements as we head up the pyramid
sums[0][0]
end
def to_s
"Pyramid:\n" << @data.map { |line| line.join " " }.join("\n")
end
end
def calculate_paths_for_files(paths)
paths.each do |path|
if File.exists? path
text = File.read path
pyramid = Pyramid.new text
puts pyramid
puts "Min Path: #{pyramid.min_path}"
end
puts ""
end
end
if __FILE__ == $0
calculate_paths_for_files ARGV
end
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
29
51 14
68 17 57
50 27 29 48
16 69 87 40 31
93 38 53 60 4 23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment