Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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

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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした