Search code examples
arraysmathpermutationcombinationsdigits

Tricky math! K arrays of N size(total KxN), need all possible permutations of size N


So for example I have: two arrays of size 3 containing

[1,2,3] and [7,8,9]

and now I need to figure out all possible permutations if I were to place them into one array of size N. They don't all need to be included(well obviously they can't because the array is too small)

Rule: Each number must be in its own index on the new permutation (So the number 1 is in index 0, it must be in index 0 of the new permutation). Note: the digits are always distinct

So the solution would be(order of these arrays does not matter):

[1,2,3]
[1,8,3]
[1,2,9]
[1,8,9]
[1,2,9]
[7,2,3]
[7,8,3]
[7,8,9]
[7,2,9]

But now I need to program this for any number of arrays; they will always have the same size.

Any hints?


Solution

  • For each index there are two choices. Therefore, there are 2^3 = 8 permutations. The solution:

    results := [[]]
    for a, b in A, B
        results :=
            results.map(result => a + result) +
            results.map(result => b + result)
    

    Where + denoted concatenation