I am in need of a function that meets the following criteria:
- Given the dimensions of an array, return all possible combination arrays based on the given numbers.
- The length of the given array should be equal to the length of the array returned.
- The size of the combinations should be the result of multiplying the numbers in the given array. For example: given [2, 2], the size would be 2*2=4; given [2, 1, 2], the size would be 2*1*2=4.
- Subtracting 1 from the number in the given array gives you the maximum number for that column.
I understand it might not be very clear, so let's look at some examples:
given: [1, 1]
return: [[0, 0]]
given: [2, 2]
return: [[0, 0], [0, 1], [1, 0], [1, 1]]
given: [2, 3]
return: [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2]]
given: [3, 3]
return: [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
given: [1, 1, 1]
return: [[0, 0, 0]]
given: [1, 1, 2]
return: [[0, 0, 0], [0, 0, 1]]
given: [2, 1, 2]
return: [[0, 0, 0], [0, 0, 1], [1, 0, 0], [1, 0, 1]]
given: [2, 2, 2]
return: [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]
Is there a way I can implement this function using lodash, Immutable.js, or any other libraries? Thank you.
===========UPDATED===========
I have finally resolved the issue by utilizing the cartesian product feature of js-combinatorics along with lodash.
Firstly, I was able to easily convert the given array into separate arrays:
import _ from 'lodash';
const givenArr = [2, 1, 2];
const arr = givenArr.map((v) => _.range(v));
console.log(arr); // [[0, 1], [0], [0, 1]]
Then, passing these transformed arrays to the js-combinatorics API as follows:
const cp = Combinatorics.cartesianProduct([0, 1], [0], [0, 1]);
console.log(cp.toArray());
// [ [ 0, 0, 0 ], [ 1, 0, 0 ], [ 0, 0, 1 ], [ 1, 0, 1 ] ]