Skip to content

Instantly share code, notes, and snippets.

@tuzz
Created July 22, 2016 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tuzz/535962962d18ef446457368cc33d12cc to your computer and use it in GitHub Desktop.
Save tuzz/535962962d18ef446457368cc33d12cc to your computer and use it in GitHub Desktop.
Generates combinations from an array
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