1
2

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 3 years have passed since last update.

【Javascript】ランダムな整数を桁指定で作る方法

Posted at

ちょっと難しかったのでメモします。

まず、基本として Math.random() は、 0以上1未満のランダムな数を作成します。

for (let i = 0; i < 3; i++){
    console.log(Math.random())
}
// 0.22040365239483273
// 0.5152515151239232
// 0.44932315151766145

整数にするためには、小数点を切り捨てなければいけません。
Math.floor() は、引数として与えた数以下の最大の整数を返します。

for (let i = 0; i < 3; i++){
    console.log(Math.floor(Math.random()))
}

// 0
// 0
// 0

ここで、1桁、つまり0~9の整数を出力したいとします。
その時は、以下のようにします。


for (let i = 0; i < 3; i++){
    console.log(Math.floor(Math.random()*10))
}

// 6
// 9
// 7

解説は以下の通りです。

Math.random() Math.random()*10 Math.floor(Math.random()*10)
0.635... 6.35... 6
0.992... 9.92... 9
0.781... 7.81... 7

次に、2桁、つまり10~99の整数を出力したいと思います。
その時は、以下のようにします。

for (let i = 0; i < 3; i++){
    console.log(Math.floor(Math.random()*(99 + 1 - 10))) + 10
}

まず、Math.floor(Math.random()*(99 + 1 - 10)) つまり Math.floor(Math.random()*90) では、0~89の整数が生成されます。
その数に10を足すと10~99の数を出力できます。

これらを一般化すると以下のようになります。


let min = <最小値> ;
let max = <最大値> ;

for (let i = 0; i < 3; i++){
    console.log(Math.floor( Math.random() * (max + 1 - min) ) + min)
}
1
2
0

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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?