I would like to generate all permutations of elements in a multi array in javascript (or the algorithm):
Input:
[
['a', 'b', 'c', 'd'],
['e', 'f', 'g'],
['h', 'i']
]
Output:
[
['a', 'e', 'h'],
['a', 'e', 'i'],
['a', 'f', 'h'],
...
['d', 'g', 'i']
]
Note: I don't want the permutations of ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'] because i don't want results like: ['a', 'b', 'c'].
Note2: I'm only interested in solutions that support input of N-dimension array.
Thanks!
If you like functional programming, you can use lift on Array type. In my case, I've used RamdaJS for the sake of simplicity:
const input = [
['a', 'b', 'c', 'd'],
['e', 'f', 'g'],
['h', 'i']
]
const output = R.lift ( ( x, y, z ) => [ x, y, z ] ) ( ...input )
console.log( output )
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
Here's a vanilla JavaScript lift3 implementation:
const input = [
['a', 'b', 'c', 'd'],
['e', 'f', 'g'],
['h', 'i']
]
const flatten = array => [].concat.apply ( [], array )
// Array#flatMap please! ;-)
const ap = funs => array => flatten ( funs.map ( f => array.map ( f ) ) )
const lift3 = f => array1 => array2 => array3 =>
ap ( ap ( array1.map ( f ) ) ( array2 ) ) ( array3 )
const output = lift3 ( x => y => z => [ x, y, z ] ) ( input[0] ) ( input[1] ) ( input[2] )
console.log( output )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With