I have a list [‘a’, ‘b’, ‘c’, ‘d’]
We can imagine each letter as a player. The goal is to produce all possible teams of 3. In this case the desired output would be…
['a', 'b', 'c']
['a', 'b', 'd']
['a', 'c', 'd']
['b', 'c', 'd']
Atleast I think this is all possible combinations, correct me if I am wrong.
I wrote this but does not produce the desired input. If I remove the data[j+1]
line and expect results for a team of 2 instead of 3 it works which is interesting.
for(let i = 0; i < data.length; i++){
for(let j = i + 1; j < data.length; j++){
team = [data[i], data[j], data[j+1]]
}
}
How can I produce the desired output?
3
Answers
Just add a third loop layer.
Recursion can be used for a more general solution.
Here’s the recursive approach to find the combination from an array of string.
Well, I am just thinking of a more mathematical way to explain it if learner wanna understand more.
Assume that your "combinations" are not repeating. We know the number of solutions is strictly
nCr
. Whichn
is the size of your set andr
is the size of the subset.In Math, we can present it in sets.
For a random set I can make up rn
0 1 2 3 4 5 6 7
🙂What we want is to avoid repeating combinations.
One of the easy way to do it is via a sorting algorithm.
As an example, for a subset size of 3. we already got
0 1 (2/3/4/5/6/7)
.The next round will be
0 2 (3/4/5/6/7)
That the selection set
(3/4/5/6/7)
are greater than the last chosen2
. So it eliminates the chance of getting0 2 1
As long as you keep the data set in
order
(Which is ordered with your decision), you can pretty much solve it with any technique (recursive, loops, or even repeatedly push and pop a container). The guys demonstrated some of the recursive implementations for the problem.Alternatively…
About the harder math way to do it… I am not 100% sure how to do it. But I think it would be interesting to share.
Note that the presence of an element can be considered a binary state.
Which makes
0 1 2 3 4 5 6 7
11111111
. Then0 1 2
would be11100000
.That makes it potentially possible to have a mapping function. With inputs
n r i
, we would be able to find thei th
combination given in the recursive.The reason I suggest this is that…
nCr
could have exponential growth. Withn=100,r=50
you already have a super large number. Which isn’t very helpful.With this mapping function(possibly using hash?), you could present
100C50
combinations with… An array size of "100", a "search" bitset with 100 bits.Fantastic!