I need to put the numbers from low
to high
in an array randomly.
For example given: low = 10, high = 15 a result like [ 12, 13, 10, 14, 11]
is good.
This is a simple algorithm: iterate from low to high and try to fill in the empty slots on an array.
const low = 1000
const high = 1010
const diff = high - low
const arr = new Array(diff)
for (var i = low; i < high; i++) {
let success = false
while(!success) {
const index = Math.floor(Math.random() * diff)
if (arr[index] === undefined) {
arr[index] = i
success = true
}
console.log(`${index} was ${success ? 'available' : 'taken'}`)
}
}
console.log(arr)
The problem is: in the end where most of the elements are filled, it is harder to find an unoccupied slot in the array.
My question is: is there an algorithm that constantly generates unique new numbers until all the numbers are consumed?
Another way to think about it is an algorithm that shuffles an array the most efficient and quickest way.