Created
January 29, 2020 10:08
-
-
Save mugyu/f82171e517b81735ae041c59f2d2e46c to your computer and use it in GitHub Desktop.
JavaScrpt の Array に shuffle メソッドを実装 Fisher–Yates shuffle
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
Array.prototype.shuffle = function() { | |
var array = this; | |
for(var i = array.length - 1; i > 0; --i) { | |
// V8 の Math.random() のアルゴリズムは xorshift128+ らしい | |
var j = Math.floor(Math.random() * i); | |
var tmp = array[i]; | |
array[i] = array[j]; | |
array[j] = tmp; | |
} | |
return array; | |
} | |
console.log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].shuffle()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment