Skip to content

Instantly share code, notes, and snippets.

@xiaohui-zhangxh
Created September 28, 2013 06:18
Show Gist options
  • Save xiaohui-zhangxh/6739032 to your computer and use it in GitHub Desktop.
Save xiaohui-zhangxh/6739032 to your computer and use it in GitHub Desktop.
Get all unsorted combinations for a certain number items of array
def combine(arr, size)
return [] if size > arr.size || size <= 0
return [arr] if size == arr.size
return arr.map{|item| [item]} if size == 1
last = arr[-1]
left = arr[0..-2]
a = combine(left, size - 1).map{|item| item + [last]}
b = combine(left, size)
return a + b
end
def combine_count(arr, size)
x = arr.size
y = size
a = 1
b = 1
size.times do
a *= x
x -= 1
b *= y
y -= 1
end
return a / b
end
def combine_test(arr, size)
combine(arr, size).size == combine_count(arr, size)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment