Reputation: 277
I think this is somewhat a combinatorics problem, but its been so long since i've done that that im quite rusty. I have a dynamic number of arrays, each with a dynamic number of elements. I am trying to get the unique combination of all items within each array. For example, if I have 3 arrays
['a','b','c']
['d',e']
['f','g']
Then i would expect to get
['a','d','f'],
['a','e','f'],
['a','d','g'],
['a','e','g'],
['b','d','f'],
['b','e','f'],
['b','d','g'],
['b','e','g'],
['c','d','f'],
['c','e','f'],
['c','d','g'],
['c','e','g']
Really struggling to write the code dynamically since the number of arrays and the number of elements in each array is not known ahead of time.
Upvotes: 0
Views: 45
Reputation: 146
I think your problem can solved using a recursive algorithm:
Input: arrs (a array of arrays)
Output: combs (array of all possible combinations)
arrs = ??? # this variable provide input arrays, like [[1,2,3], [4,5]]
combs = [] # this variable store the answer
def get_combs(arrs, i, currentComb):
if i >= len(arrs):
combs.append(list(currentComb))
return
for elem in arrs[i]:
currentComb.append(elem)
get_combs(arrs, i+1, currentComb)
currentComb.pop()
get_combs(arrs, 0, []) // after this call, the combs get the desired answer.
The code above is in Python and pretty dirty.
Upvotes: 1
Reputation: 118
Using Python, we can achieve this in multiple ways,
a = ['a','b','c']
b = ['d','e']
c = ['f','g']
Using Multiple FOR Loops
for i in a:
for j in b:
for k in c:
print([i, j, k])
Output:
['a', 'd', 'f']
['a', 'd', 'g']
['a', 'e', 'f']
['a', 'e', 'g']
['b', 'd', 'f']
['b', 'd', 'g']
['b', 'e', 'f']
['b', 'e', 'g']
['c', 'd', 'f']
['c', 'd', 'g']
['c', 'e', 'f']
['c', 'e', 'g']
Using Lists Comprehensions:
d = [[i, j, k] for i in a for j in b for k in c]
d
** Output:**
[['a', 'd', 'f'],
['a', 'd', 'g'],
['a', 'e', 'f'],
['a', 'e', 'g'],
['b', 'd', 'f'],
['b', 'd', 'g'],
['b', 'e', 'f'],
['b', 'e', 'g'],
['c', 'd', 'f'],
['c', 'd', 'g'],
['c', 'e', 'f'],
['c', 'e', 'g']]
We can also use itertools module to generate the permutation combinations.
Upvotes: 0