Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!