From df274ab42eca61ce49e2d417b54afe17f21da554 Mon Sep 17 00:00:00 2001 From: Vinay Sagar Sharma Date: Sun, 11 Oct 2020 22:37:44 +0530 Subject: [PATCH] added De-facto unbiased shuffle algorithm --- De-facto unbiased shuffle/Fisher-Yates.js | 24 +++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 De-facto unbiased shuffle/Fisher-Yates.js diff --git a/De-facto unbiased shuffle/Fisher-Yates.js b/De-facto unbiased shuffle/Fisher-Yates.js new file mode 100644 index 0000000000..21e52dc9f3 --- /dev/null +++ b/De-facto unbiased shuffle/Fisher-Yates.js @@ -0,0 +1,24 @@ +function shuffle(array) { + var currentIndex = array.length, + temporaryValue, + randomIndex; + + // While there remain elements to shuffle... + while (0 !== currentIndex) { + // Pick a remaining element... + randomIndex = Math.floor(Math.random() * currentIndex); + currentIndex -= 1; + + // And swap it with the current element. + temporaryValue = array[currentIndex]; + array[currentIndex] = array[randomIndex]; + array[randomIndex] = temporaryValue; + } + + return array; +} + +// Used like so +var arr = [2, 11, 37, 42]; +shuffle(arr); +console.log(arr); pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy