Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

163
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda