I understand you can shuffle an array in JavaScript using a Fisher-Yates Shuffle. This however uses Math.random for it's random numbers. I was wondering if you could get a better shuffle using window.crypto.getRandomValues() for the random number source?
I have had a go below which works. The getRandomIntInRange() function uses rejection sampling and example specified here.
Please let me know if this is the right way to do it, or if you can think of a better way to do it. JSFiddle here.
$(document).ready(function()
{
var dataArray = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14'];
var shuffledArray = shuffleArray(dataArray);
console.log(shuffledArray);
});
function getRandomIntInRange(min, max) {
var range = max - min + 1;
var maxRange = 256;
var byteArray = new Uint8Array(1);
// Fill byteArray with 1 random number
window.crypto.getRandomValues(byteArray);
// If outside of range, get another
if (byteArray[0] >= Math.floor(maxRange / range) * range)
{
return getRandomIntInRange(min, max);
}
return min + (byteArray[0] % range);
}
function shuffleArray(dataArray) {
var counter = dataArray.length, temp, index;
while (counter > 0)
{
index = getRandomIntInRange(0, counter - 1);
counter--;
temp = dataArray[counter];
dataArray[counter] = dataArray[index];
dataArray[index] = temp;
}
return dataArray;
}