Is there a more functional way to create a 2d array in Javascript than what I have here? Perhaps using .apply?
generatePuzzle(size) {
let puzzle = [];
for (let i = 0; i < size; i++) {
puzzle[i] = [];
for (let j = 0; j < size; j++) {
puzzle[i][j] = Math.floor((Math.random() * 200) + 1);
}
}
return puzzle;
}
For instance, in python, you can do something like [[0]*4]*4 to create a 4x4 list
const repeat = (fn, n) => Array(n).fill(0).map(fn);
const rand = () => Math.floor((Math.random() * 200) + 1);
const puzzle = n => repeat(() => repeat(rand, n), n);
And then puzzle(3), eg, will return a 3x3 matrix filled with random numbers.
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