LoginSignup
1
1

More than 5 years have passed since last update.

0以上n未満のランダムな配列をつくる

Last updated at Posted at 2016-06-29

さくっと作れないくらいのレベルなのでメモ。

[0, n)までのランダムなn個の配列を作成する

randomArray.js
function randomArray(n) {
    var arr = [];
    var num;
    var i = 0;
    while(i < n) {
        num = Math.floor(Math.random() * n);
        if(~arr.indexOf(num)) continue;
        arr.push(num);
        i++;
    }

    return arr;
}

// [0, 10)のランダム配列
randomArray(10);
出力結果
[5, 9, 8, 3, 2, 1, 0, 4, 7, 6]

[0, n)の中からランダムでm個取得する

nCmです。
実は上のとほぼ同じで、ループ部分の上限をmにすればかんせい。

combination.js
function combination(n, m) {
    var arr = [];
    var num;
    var i = 0;
    while(i < m) {
        num = Math.floor(Math.random() * n);
        if(~arr.indexOf(num)) continue;
        arr.push(num);
        i++;
    }

    return arr;
}

// [0, 100)から10個ランダムに取った数値の配列
combination(100, 10);
出力結果
[48, 86, 17, 19, 79, 21, 76, 4, 37, 27]

その他

[1, n] ( あるいは(0, n] )にしたいときはMath.floor => Math.ceilにかえればいけるはず。

1
1
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
1
1