Last active
December 3, 2019 14:36
-
-
Save tkfm-yamaguchi/f0e053c2b16baf2b5c503abd8eea9c69 to your computer and use it in GitHub Desktop.
RIoW for Array#combination, but it is a single method.
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
require "test/unit" | |
def combination(a, k) | |
return a.map{|n| [n] } if k == 1 | |
a[0..(a.size - k)].each_with_index.reduce([]) do |c, (n, i)| | |
c + combination(a[i.succ..-1], k - 1).map{|r| [n, *r]} | |
end | |
end | |
class TestCmb < Test::Unit::TestCase | |
test 'it returns single size array of array when k = 1' do | |
assert do | |
combination([1,2,3], 1) == [[1], [2], [3]] | |
end | |
end | |
test 'it returns combinations for minimum condition' do | |
assert do | |
combination([1,2], 2) == [[1,2]] | |
end | |
end | |
test 'it returns array of combinations for small array' do | |
assert do | |
combination([1,2,3], 2) == [[1,2], [1,3], [2,3]] | |
end | |
end | |
test 'it returns array of combinations for modarite size array' do | |
combination([1,2,3,4,5,6,7], 4) == [[1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 3, 6], [1, 2, 3, 7], [1, 2, 4, 5], [1, 2, 4, 6], [1, 2, 4, 7], [1, 2, 5, 6], [1, 2, 5, 7], [1, 2, 6, 7], [1, 3, 4, 5], [1, 3, 4, 6], [1, 3, 4, 7], [1, 3, 5, 6], [1, 3, 5, 7], [1, 3, 6, 7], [1, 4, 5, 6], [1, 4, 5, 7], [1, 4, 6, 7], [1, 5, 6, 7], [2, 3, 4, 5], [2, 3, 4, 6], [2, 3, 4, 7], [2, 3, 5, 6], [2, 3, 5, 7], [2, 3, 6, 7], [2, 4, 5, 6], [2, 4, 5, 7], [2, 4, 6, 7], [2, 5, 6, 7], [3, 4, 5, 6], [3, 4, 5, 7], [3, 4, 6, 7], [3, 5, 6, 7], [4, 5, 6, 7]] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment