Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
56
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

@komaji504

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

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

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は偏る

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
56
Help us understand the problem. What are the problem?