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.
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)