Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate 2d array with Javascript/es6 [duplicate]

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

like image 307
denvaar Avatar asked Mar 29 '26 17:03

denvaar


1 Answers

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.

like image 104
Jonah Avatar answered Apr 01 '26 10:04

Jonah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!