Skip to content

Instantly share code, notes, and snippets.

@switchspan
Created May 7, 2013 21:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save switchspan/5536508 to your computer and use it in GitHub Desktop.
Save switchspan/5536508 to your computer and use it in GitHub Desktop.
Partition function - James Edward Gray II's ruby implementation
# The partition (combinatoric partition theory) function for a given number
def partition(largest, rest = Array.new, &block)
block.call([largest] + rest)
(rest.first || 1).upto(largest / 2) do |i|
partition(largest - i, [i] + rest, &block)
end
end
# call the partition function with "5" as a test
partition(5) { |nums| p nums if nums[0] != 5 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment