Skip to content

Instantly share code, notes, and snippets.

@flada-auxv
Last active August 24, 2016 04:44
Show Gist options
  • Save flada-auxv/536a4f7e967214d33041b757f5936576 to your computer and use it in GitHub Desktop.
Save flada-auxv/536a4f7e967214d33041b757f5936576 to your computer and use it in GitHub Desktop.
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