Last active
June 30, 2018 11:54
-
-
Save loretoparisi/c09e131d0b731c64fff498b288eba78e to your computer and use it in GitHub Desktop.
Shuffle Array in JavaScript
This file contains 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
/** | |
* Shuffle array | |
* Fisher-Yates (aka Knuth) Shuffle | |
*/ | |
let shuffle = (array) => { | |
var currentIndex = array.length, temporaryValue, randomIndex; | |
while (0 !== currentIndex) { | |
randomIndex = Math.floor(Math.random() * currentIndex); | |
currentIndex -= 1; | |
temporaryValue = array[currentIndex]; | |
array[currentIndex] = array[randomIndex]; | |
array[randomIndex] = temporaryValue; | |
} | |
return array; | |
} |
Example:
shuffle([...Array(10).keys()])
shuffle([...Array(1000).keys()])
Performances:
var t0,t1;
t0 = performance.now();
shuffle([...Array(10).keys()])
t1 = performance.now();
console.log("10:"+(t1 - t0) + " msec.")
t0 = performance.now();
shuffle([...Array(100).keys()])
t1 = performance.now();
console.log("100:"+(t1 - t0) + " msec.")
t0 = performance.now();
shuffle([...Array(1000).keys()])
t1 = performance.now();
console.log("1000:"+(t1 - t0) + " msec.")
t0 = performance.now();
shuffle([...Array(10000).keys()])
t1 = performance.now();
console.log("10000:"+(t1 - t0) + " msec.")
t0 = performance.now();
shuffle([...Array(100000).keys()])
t1 = performance.now();
console.log("100000:"+(t1 - t0) + " msec.")
t0 = performance.now();
shuffle([...Array(1000000).keys()])
t1 = performance.now();
console.log("1000000:"+(t1 - t0) + " msec.")
86.6999999852851 msec.
10:0.10000000474974513 msec.
100:0 msec.
1000:0.20000000949949026 msec.
10000:2.199999988079071 msec.
100000:18.099999986588955 msec.
1000000:100.19999998621643 msec.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For Random Number generation see https://gist.github.com/loretoparisi/498f8fe3a6bd789615a7d901fc4d78c7