main
 1require 'spec_helper'
 2
 3describe "combinations of strings" do
 4  def permutation(string)
 5    return [string] if string.size < 2
 6    return [string, string.reverse] if string.size == 2
 7
 8    character = string[-1]
 9    permutation(string.chop).inject([]) do |results, permutation|
10      0.upto(permutation.size) do |position|
11        results << permutation.clone.insert(position, character)
12      end
13      results
14    end
15  end
16
17  it 'produces each combination of 1' do
18    expect(permutation('a')).to match_array(['a'])
19  end
20
21  it 'produces each combination of 2' do
22    # 'ab' => ["ab", "ba"]
23    results = permutation('ab')
24    expected = 'ab'.chars.permutation.map(&:join).to_a
25    expect(results).to match_array(expected)
26  end
27
28  it 'produces each combination of 3' do
29    # 'abc' => ["abc", "acb", "bac", "bca", "cab", "cba"]
30    results = permutation('abc')
31    expected = 'abc'.chars.permutation.map(&:join).to_a
32    expect(results).to match_array(expected)
33    expect(results.length).to eql(6)
34  end
35end