From: Mischa POSLAWSKY Date: Wed, 29 Dec 2021 05:04:34 +0000 (+0100) Subject: word/quiz: fisher-yates shuffle algorithm X-Git-Tag: v1.13~65 X-Git-Url: http://git.shiar.nl/sheet.git/commitdiff_plain/26074080358f5993e59f19526704c58c1de2606f word/quiz: fisher-yates shuffle algorithm Fixes very bad randomisation in some browsers. Reference: --- diff --git a/word/quiz.js b/word/quiz.js index 70f8500..361d075 100644 --- a/word/quiz.js +++ b/word/quiz.js @@ -1,5 +1,9 @@ Array.prototype.shuffle = function () { - return this.sort(() => {return .5 - Math.random()}); + for (let i = this.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); // random index 0..i + [this[i], this[j]] = [this[j], this[i]]; // swap elements + } + return this; }; class WordQuiz {