Last active
August 24, 2016 04:44
-
-
Save flada-auxv/536a4f7e967214d33041b757f5936576 to your computer and use it in GitHub Desktop.
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
class Hoge | |
def combination(array, num) | |
return [] if num == 0 | |
return array.map {|elem| Array(elem) } if num == 1 | |
each_with_rest(array).with_object([]) {|(elem, rest), result| | |
result.push(*_combination(rest, [elem], num)) | |
} | |
end | |
def _combination(array, candidates, num, result = []) | |
each_with_rest(array).with_object(result) {|(elem, rest), result| | |
_candidates = candidates.dup << elem | |
if _candidates.count == num | |
result << _candidates | |
else | |
_combination(rest, _candidates, num, result) | |
end | |
} | |
end | |
def each_with_rest(array) | |
if block_given? | |
array.each_with_index {|elem, i| yield elem, array[i+1..-1] } | |
else | |
array.map.with_index {|elem, i| [elem, array[i+1..-1]] }.each | |
end | |
end | |
end | |
array = %w(a b c d e f g) | |
p Hoge.new.combination(array, 4) == array.combination(4).to_a |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment