75
55

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptで配列をシャッフルする方法

Last updated at Posted at 2015-06-20

調べていて多かったもの。

Array.prototype.sort()を用いる方法

例:

array.sort(function() { Math.random() - .5; });
  • 最小計算量は$O(n)$だが最悪計算量は$O(n^2)$である
  • シャッフルの結果に偏りが見られる

Fisher–Yatesアルゴリズムを用いる方法

例:

for(var i = array.length - 1; i > 0; i--){
    var r = Math.floor(Math.random() * (i + 1));
    var tmp = array[i];
    array[i] = array[r];
    array[r] = tmp;
}
  • 計算量は常に$O(n)$である
  • シャッフル結果にほとんど偏りが見られない

参考

Array#sort実装のshuffleは偏る

75
55
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
75
55

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?