Created
March 19, 2019 23:36
-
-
Save malulleybovo/168cbdca7d782402b923589f0e5b7881 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Made as proof of concept - malulleybovo@2019 | |
// A simple and fair array shuffle algorithm | |
var randomizeArray = function(arr) { | |
if (arr == null || !Array.isArray(arr)) return []; | |
arr = arr.slice(0); | |
var randArr = []; | |
while (arr.length > 1) { | |
randArr.push(arr.splice( | |
Math.floor(Math.random() * arr.length), 1)); | |
} | |
if (arr.length == 1) randArr.push(arr[0]); | |
return randArr; | |
} | |
var N = 10; // Array size | |
var M = 100000; // Number of tests | |
var deviations = []; // Standard deviation per array position | |
// Create the test array | |
var arr = []; | |
for (var i = 0; i < N; i++) arr.push(i); | |
// Test fairness of algorithm | |
for (var i = 0; i < N; i++) { | |
var prob = []; | |
for (var j = 0; j < arr.length; j++) prob.push(0); | |
// Get the distribution per element of the original array | |
for (var j = 0; j < M; j++) { | |
var testArr = randomizeArray(arr); | |
prob[arr.indexOf(parseInt(testArr[i], 10))] += 1 / M; | |
} | |
// Get standard deviation for every position of the random array | |
var avg = 0; | |
for (var j = 0; j < N; j++) { | |
avg += Math.pow(prob[j] - (1 / N), 2); | |
} | |
avg /= N; | |
avg = Math.sqrt(avg); | |
// Save results | |
deviations.push(avg); | |
} | |
console.log("Standard Deviation per Array Position: " + deviations); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment