Created
September 28, 2013 06:18
-
-
Save xiaohui-zhangxh/6739032 to your computer and use it in GitHub Desktop.
Get all unsorted combinations for a certain number items of array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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