I am trying to generate a method returning an array of every 2d arrays composed of 0's and 1's in JS in a 2d squared array. Basically, this is the same question as this one : Make every possible combination in 2D array
But in Javascript, without packages, and add a parameter for the size of the array. Like, a 2x2 would be :
let arr = new Array(2).fill(0).map(() => new Array(2).fill(0))
combinations(arr, 2) { ... }
returns :
[
[
[0, 0],
[0, 0]
],
[
[0, 0],
[0, 1]
],
[...],
[
[1, 1],
[1, 1]
]
]
I've tried with recursion but without success, any help would be appreciated.
Edit :
I am tryin =g to write a recursive function to solve this problem.
For now, I have this method :
let arr = new Array(2).fill(0).map(() => new Array(2).fill(0))
const generateCombination = (arr, n) => {
let ret = [];
let tmp;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
ret.push(arr)
arr[i][j] = 1;
generateCombination(arr.slice(), n-1)
}
}
return ret;
};
which produces this output :
[
[ [ 1, 1 ], [ 1, 1 ] ],
[ [ 1, 1 ], [ 1, 1 ] ],
[ [ 1, 1 ], [ 1, 1 ] ],
[ [ 1, 1 ], [ 1, 1 ] ],
]