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

162
Visualizações
Change random value in 2D array as efficiently as possible in JavaScript
var cells = [
    [1, 2, 3, 5],
    [1, 1, 2, 3],
    [1, 1, 1, 2],
    [0, 1, 0, 1]
]

The challange is to pick one equally random 0 from cells and change it randomly to a 1 or 2.

The chance of it changing to a 1 should be 90%. The chance of a 2 10%.

cells will always be a 4x4 array.

I am wondering if there are some faster solutions (even if it is uglier) that I cannot find. Anything slighly faster is welcome as an answer!

Your solution should rather not use external libraries.

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

0

function addRandomTile(cells) {
  let empty = 0

  for (let x = 0; x < 4; x++) {
    for (let y = 0; y < 4; y++) {
      if (cells[x][y] == 0) empty++
    }
  }
  if (empty == 0) return false // return if no cells available

  let choice = Math.floor(Math.random() * empty),
      value = Math.random() < .9 ? 1 : 2

  empty = -1

  for (let x = 0; x < 4; x++) {
    for (let y = 0; y < 4; y++) {
      if (cells[x][y] == 0) empty++

      if (empty == choice) {
        cells[x][y] = value
        return
      }
    }
  }
}

var cells,
    time = Date.now(),
    ops = 10 ** 6

for (let i = 0; i < ops; i++) {
  cells = [
      [1, 2, 3, 5],
      [1, 1, 2, 3],
      [1, 1, 1, 2],
      [0, 1, 0, 1]
  ]
  addRandomTile(cells)
}
time = Date.now() - time
console.log(Math.floor(ops / time) * 1000, 'ops/sec') // My pc gets 5200000 ops/sec ±3%
// Speed depends on your pc
// https://jsbench.me/ got 6.15 ops/s ± 0.53%

console.log(cells)

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