-
-
Save tomstuart/51ea0775d6d9a8e20abf1fac8d60dbd6 to your computer and use it in GitHub Desktop.
Generates combinations from an array
This file contains hidden or 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.each_index.map { |i| array.drop(i) }.flat_map do |head, *tail| | |
combinations(tail, length - 1).map do |combination| | |
[head] + 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