Looking to create a function that will generate an array of all possible 2D arrays consisting of 0s and 1s in JavaScript within a square 2D array. Essentially, this is similar to the question posed here: Make every possible combination in 2D array
However, I want to achieve this in Javascript without using any external packages. Also, I would like to include a parameter for the size of the array. For example, a 2x2 grid would look like this:
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 have attempted recursion but haven't been successful so far. Any assistance on this matter would be greatly appreciated.
Edit :
I am working on writing a recursive solution for this issue.
Currently, my method looks like this:
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;
};
This implementation currently produces the following output :
[
[ [ 1, 1 ], [ 1, 1 ] ],
[ [ 1, 1 ], [ 1, 1 ] ],
[ [ 1, 1 ], [ 1, 1 ] ],
[ [ 1, 1 ], [ 1, 1 ] ],
]