Skip to content

Instantly share code, notes, and snippets.

@gmarik
Created April 26, 2012 22:22
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 gmarik/2503689 to your computer and use it in GitHub Desktop.
Save gmarik/2503689 to your computer and use it in GitHub Desktop.
# get all combinations http://en.wikipedia.org/wiki/Combination
n = (ARGV[0] || 5).to_i
m = (ARGV[1] || 3).to_i
puts "#{n}/#{m}"
def comb(list, m, q, acc)
return if list.empty?
a, b = list[0,1], list[1..-1]
acc << (q + a) if m == 1
comb(b, m - 1, q + a, acc)
comb(b, m, q, acc)
end
comb((1..n).to_a, m, [], acc = [])
p acc
# Example
# > ruby comb.rb 5 3
# 5/3
# [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5], [2, 4, 5], [3, 4, 5]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment