I have an array which can have a max length of several hundred thousand rows. It looks like this:
arr[12] = false
arr[334] = true
arr[753] = true
arr[1001] = false
arr[1222] = true
and so on…
I want to find the fastest way to randomly select the index of a row that is true…
My initial attempt was to do this:
for(k in arr) {
if(arr[k]) {
candidate.push(k);
}
}
return Math.floor(Math.random() * candidate.length);
But it is quite slow.
Is there a better way to do it?
Ty
If the fraction of missing elements is sufficiently small it will be fast enough to just generate random indexes until you get a hit. Give it a try.