Random generator without repeated result


Random generator without repeated result



I need to put the numbers from low to high in an array randomly.


low


high



For example given: low = 10, high = 15 a result like [ 12, 13, 10, 14, 11] is good.


[ 12, 13, 10, 14, 11]



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?





No, not that I know of. If you want to generate true random numbers over a range, then there is always the chance of drawing a duplicate. If not, then you're not generating random numbers over that inclusive range.
– Tim Biegeleisen
8 mins ago






Instead of generating "random" numbers, generate a list of the numbers and shuffle it "randomly" by using something like Fisher-Yates Shuffle.
– Sani Singh Huttunen
7 mins ago






Shuffle a list containing the range you want and pop elements off it
– user3080953
6 mins ago




1 Answer
1



Instead of generating "random" numbers, generate a list of the numbers and shuffle it "randomly" by using something like Fisher-Yates Shuffle:


function getRandomArray(min, max) {
var arr = ;
for (var i = min; i < max; i++) {
arr.push(i);
}

return arr;
}

function shuffle(array) {
var m = array.length, t, i;

while (m) {

i = Math.floor(Math.random() * m--);

t = array[m];
array[m] = array[i];
array[i] = t;
}

return array;
}

var randomArr = getRandomArray(10, 15);
shuffle(randomArr);
console.log(randomArr);






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

PySpark - SparkContext: Error initializing SparkContext File does not exist

django NoReverseMatch Exception

Python Tkinter Error, “Too Early to Create Image”