How would you implement the Cartesian product of multiple arrays in JavaScript?
As an example,
cartesian([1,2],[10,20],[100,200,300]) //should be
// [[1,10,100],[1,10,200],[1,10,300],[2,10,100],[2,10,200]...]
How would you implement the Cartesian product of multiple arrays in JavaScript?
As an example,
cartesian([1,2],[10,20],[100,200,300]) //should be
// [[1,10,100],[1,10,200],[1,10,300],[2,10,100],[2,10,200]...]
it seems the community thinks this to be trivial and or easy to find a reference implementation, upon brief inspection i couldn't or maybe it's just that i like re-inventing the wheel or solving classroom-like programming problems either way its your lucky day:
full reference implementation that's relatively efficient... :-D
on efficiency: you could gain some by taking the if out of the loop and having 2 separate loops since it is technically constant and you'd be helping with branch prediction and all that mess, but that point is kind of moot in javascript
anywho, enjoy -ck
A non-recursive approach that adds the ability to filter and modify the products before actually adding them to the result set. Note the use of .map rather than .forEach. In some browsers, .map runs faster.
Plain JS brute force approach that takes an array of arrays as input.
Just converted @dummersl's answer from CoffeScript to JavaScript. It just works.
A simple "mind and visually friendly" solution.
A single line approach, for better reading with indentations.
It takes a single array with arrays of wanted cartesian items.