Michael Durrant
Michael Durrant

Reputation: 96454

How to get ALL combinations of array elements in Ruby?

If I have an array:

%w(a b c d e)
=> ["a","b","c","d","e"]

I can get some combinations with

irb(main):071:0> %w(a b c d e).combination(3).to_a
=> [["a", "b", "c"], ["a", "b", "d"], ["a", "b", "e"], ["a", "c", "d"], ["a", "c", "e"], ["a", "d", "e"], ["b", "c", "d"], ["b", "c", "e"], ["b", "d", "e"], ["c", "d", "e"]]

However that is not ALL the combinations, just the unique ones, e.g. ["e", "a", "b"] is missing

When I similarly try with s smaller array I only get one result:

irb(main):059:0> %w(a b c).combination(3).to_a  
=> [["a", "b", "c"]]

How can I get all 6 combinations, i.e. for ['a', 'b', 'c'] I want to get

[['a','b','c'], ['a','c','b'], ['b', 'a', 'c'], ['b', 'c', 'a'], ['c', 'a', 'b'], ['c', 'b', 'a']

Similarly for [1,2,3,4] if I want all the 3 digit combo I should get

irb(main):074:0> [[1,2,3],[1,2,4],[1,3,2],[1,3,4],[1,4,2],[1,4,3],  [2,1,3],[2,1,4],[2,3,4],[2,3,1],[2,4,1],[2,4,2],  [3,1,2],[3,1,4],[3,2,3],[3,2,4],[3,4,2],[3,4,1]]

?

Upvotes: 1

Views: 1096

Answers (2)

Vaibhav Jain
Vaibhav Jain

Reputation: 397

Input: str = "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".

Code :-

arr= str.chars
new_arr = []

for index in 1..arr.length do
  new_arr<< arr.permutation(index).to_a.uniq
end

puts new_arr.flatten(1).count

Upvotes: 0

kiddorails
kiddorails

Reputation: 13014

You are looking for permutation instead of combination.

In combinations, we do not care about the order of the elements, and only care about the presence of all the elements in the set.

[1,2,3,4].permutation(3).to_a
#=> [[1, 2, 3], [1, 2, 4], [1, 3, 2], [1, 3, 4], [1, 4, 2], [1, 4, 3], [2, 1, 3], [2, 1, 4], [2, 3, 1], [2, 3, 4], [2, 4, 1], [2, 4, 3], [3, 1, 2], [3, 1, 4], [3, 2, 1], [3, 2, 4], [3, 4, 1], [3, 4, 2], [4, 1, 2], [4, 1, 3], [4, 2, 1], [4, 2, 3], [4, 3, 1], [4, 3, 2]]

Upvotes: 3

Related Questions