Created
July 22, 2016 14:32
-
-
Save tuzz/535962962d18ef446457368cc33d12cc to your computer and use it in GitHub Desktop.
Generates combinations from an 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
require "rspec" | |
def combinations(array, length) | |
if length.zero? | |
[[]] | |
else | |
array.flat_map.with_index do |element, index| | |
tail = array[(index + 1)..-1] | |
combinations(tail, length - 1).map do |combination| | |
[element] + combination | |
end | |
end | |
end | |
end | |
RSpec.describe "combinations" do | |
it "works for combinations of 0" do | |
expect(combinations([], 0)).to eq [[]] | |
expect(combinations([1], 0)).to eq [[]] | |
expect(combinations([1, 2], 0)).to eq [[]] | |
expect(combinations([1, 2, 3], 0)).to eq [[]] | |
end | |
it "works for combinations of 1" do | |
expect(combinations([], 1)).to eq [] | |
expect(combinations([1], 1)).to eq [[1]] | |
expect(combinations([1, 2], 1)).to eq [[1], [2]] | |
expect(combinations([1, 2, 3], 1)).to eq [[1], [2], [3]] | |
end | |
it "works for combinations of 2" do | |
expect(combinations([], 2)).to eq [] | |
expect(combinations([1], 2)).to eq [] | |
expect(combinations([1, 2], 2)).to eq [[1, 2]] | |
expect(combinations([1, 2, 3], 2)).to eq [[1, 2], [1, 3], [2, 3]] | |
end | |
it "works for combinations of 3" do | |
expect(combinations([], 3)).to eq [] | |
expect(combinations([1], 3)).to eq [] | |
expect(combinations([1, 2], 3)).to eq [] | |
expect(combinations([1, 2, 3], 3)).to eq [[1, 2, 3]] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment