Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

112
Visualizações
How to create a 2d array with only two elements and randomize it?

I've created a 2d array where subArrays include only 0 and 1 generated via Math.random() function. Currently it's implemented with for loops.
Now I'm trying to get the same output using es6 functions, but could't solve it.

Here is the solution with for loops

const rows = 25;
const cols = 35;

const randomGrid = () => {
  const grid = [];
  for (let i = 0; i < rows; i++) {
    const row = [];
    for (let j = 0; j < cols; j++) {
      row.push(Math.floor(Math.random() * 2));
    }
    grid.push(row);
  }
  return grid;
};

console.log(randomGrid())

And here I am trying to achieve the same output with modern js functions. I managed only two create the 2d Array, but could't populate with 0 and 1 in random order. Currently elements are undefined.

const rows = 25;
const cols = 35;

const randomTwoDArr = (numOfRows, numOfCols) => {
  const grid = [];
  return Array(numOfRows)
    .fill()
    .map((row) => Array(numOfCols));
};

console.log(randomTwoDArr(rows, cols));

Any help will be appreciated.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can do this using Array.from as:

const rows = 25;
const cols = 35;

const randomGrid = () => {
    return Array.from({ length: rows }, () => {
        return Array.from({ length: cols }, () => Math.floor(Math.random() * 2));
    });
};

console.log(randomGrid());

about 4 years ago · Juan Pablo Isaza Relatório

0

You're on the right track, Just complete creating columns with Array(numOfCols).fill() and fill it with random numbers 1 or 0 .map(x=>Math.floor(Math.random() * 2))

const rows = 25;
const cols = 35;

const randomTwoDArr = (numOfRows, numOfCols) => {
  const grid = [];
  return Array(numOfRows)
    .fill()
    .map((row) => Array(numOfCols).fill().map(x=>Math.floor(Math.random() * 2)));
};

console.log(randomTwoDArr(rows, cols));

about 4 years ago · Juan Pablo Isaza Relatório

0

you can use Array.from

const rows = 25;
const cols = 35;

const randomTwoDArr = (numOfRows, numOfCols) => {
  const grid = [];
  return Array.from({length:numOfRows}, _ => Array.from({length:numOfCols }, () => Math.random() > 0.5 ? 1: 0))
    
};

console.log(randomTwoDArr(rows, cols));

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda