From 751ed446d93df66f8f22d742ae1890c82fdb300e Mon Sep 17 00:00:00 2001 From: Mathias Rav Date: Sat, 27 Oct 2018 20:50:31 +0200 Subject: [PATCH] Fix shuffle algorithm for friends page Implement Fisher-Yates shuffle [1] to ensure that each random permutation is equally likely to be produced. The algorithm "repeatedly pick two random indices i and j between 0 and N-1 and swap element i and j" is a simple, straightforward algorithm, but unfortunately it tends to produce some random orderings more frequently than others. There is an equally simple algorithm by Fischer and Yates that does not have the same problem: "for i = 0 to N-1, pick a random index j between 0 and i and swap element i and j". [1]: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle --- _includes/friends.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/_includes/friends.js b/_includes/friends.js index 3eb3d9f47..9f19fd298 100644 --- a/_includes/friends.js +++ b/_includes/friends.js @@ -14,9 +14,8 @@ function swapDiv(e1, e2){ function shuffle() { var friends = document.querySelectorAll(".friend"); for (var i = 0; i < friends.length; i++) { - var r1 = Math.floor(Math.random() * friends.length); - var r2 = Math.floor(Math.random() * friends.length); - swapDiv(friends[r1], friends[r2]); + var r = Math.floor(Math.random() * (i + 1)); + swapDiv(friends[r], friends[i]); } }