Skip to content

Instantly share code, notes, and snippets.

@joejag
Created September 27, 2012 22:09
Show Gist options
  • Save joejag/3796747 to your computer and use it in GitHub Desktop.
Save joejag/3796747 to your computer and use it in GitHub Desktop.
Natural Number Additions in Ruby
class NaturalNumberAdditions
def self.for num
NaturalNumberAdditions.new.calc(num)
end
def calc num
return [] if num == 1
pairs_for(num) | previous_additions_plus_one(num)
end
def pairs_for num
pairs = []
(1..num).each do |lhs|
(1..num).each do |rhs|
next if lhs < rhs
pairs << "#{lhs} + #{rhs}" if lhs + rhs == num
end
end
pairs
end
def previous_additions_plus_one num
NaturalNumberAdditions.for(num - 1).map { |previous| "#{previous} + 1" }
end
end
(1..10).each do |num|
puts "#{num} is #{NaturalNumberAdditions.for(num).join(', ')}"
end
# produces
# 1 is
# 2 is 1 + 1
# 3 is 2 + 1, 1 + 1 + 1
# 4 is 2 + 2, 3 + 1, 2 + 1 + 1, 1 + 1 + 1 + 1
# 5 is 3 + 2, 4 + 1, 2 + 2 + 1, 3 + 1 + 1, 2 + 1 + 1 + 1, 1 + 1 + 1 + 1 + 1
# 6 is 3 + 3, 4 + 2, 5 + 1, 3 + 2 + 1, 4 + 1 + 1, 2 + 2 + 1 + 1, 3 + 1 + 1 + 1, 2 + 1 + 1 + 1 + 1, 1 + 1 + 1 + 1 + 1 + 1
# ....
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment