Skip to content

Instantly share code, notes, and snippets.

@tomstuart
Forked from tuzz/combinations_spec.rb
Created July 22, 2016 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomstuart/51ea0775d6d9a8e20abf1fac8d60dbd6 to your computer and use it in GitHub Desktop.
Save tomstuart/51ea0775d6d9a8e20abf1fac8d60dbd6 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.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