hoge(min, max) => min + Math.floor(Math.random() * (max - min + 1))
console.log(hoge(1,9)) // 1~9の数字どれか一つ
Math.random()関数は、 0 以上 1 未満 (0 は含むが、 1 は含まない) の範囲で浮動小数点の擬似乱数を返します。その範囲ではほぼ均一な分布で、ユーザーは範囲の拡大をすることができます。実装側で乱数生成アルゴリズムの初期シードを選択します。ユーザーが初期シードを選択、またはリセットすることは出来ません。
console.log(Math.random()); // 0.2999647683533573
console.log(Math.random()); // 0.4461227301606392
console.log(Math.random()); // 0.7556742909808709
Math.floor()関数は引数内に定義した数字の小数点を切り捨てるものとなります。
console.log(Math.floor(5.95));
// expected output: 5
console.log(Math.floor(5.05));
// expected output: 5
console.log(Math.floor(5));
// expected output: 5
console.log(Math.floor(-5.05));
// expected output: -6
console.log(Math.floor(Math.random())); // 0
Math.randomは0~0.999…の乱数になるので何回繰り返しても0を返します。
console.log(Math.random() * 2); // 1.9222419935166877
console.log(Math.random() * 2); // 0.2760383296721032
console.log(Math.random() * 2); // 1.5002908195501692
===========================================================
console.log(Math.floor(Math.random() * 2)); // 1
console.log(Math.floor(Math.random() * 2)); // 0
console.log(Math.floor(Math.random() * 2)); // 1
次にMath.randomに2を掛けてみましょう。
ご覧の通り、0 ~ 1.999….の値となるためMath.floor()で囲うと0,1のどちらかが出力されます。
console.log(Math.random() * 4); // 1.463454845003442
console.log(Math.random() * 4); // 2.7493824619815657
console.log(Math.random() * 4); // 3.051782069628058
============================================================
console.log(Math.floor(Math.random() * 4)); // 1
console.log(Math.floor(Math.random() * 4)); // 2
console.log(Math.floor(Math.random() * 4)); // 3
Math.random()の値は0 ~ 3.999…なので、1,2,3のどれかがMath.floor内に出力されます、 お分かりだとは思いますが、Math.randomに掛けた数字に対してMath.floor()の値が-1少ないとが確認できたと思います。
そして5~11の中で乱数を取りたいとなったとしましょう。
この中からの選択となるので7つの選択肢があることになります。
選択値である7の値を出すために
(最大値) - (最小値) +1
とする必要があるわけです。
console.log(Math.floor(Math.random() * (11 - 5 + 1))); // 0
console.log(Math.floor(Math.random() * (11 - 5 + 1))); // 5
console.log(Math.floor(Math.random() * (11 - 5 + 1))); // 2
5,6,7,8,9,10,11
0,1,2,3,4,5,6,7
現在の値に+5をすると欲しい値が取れていることがわかりました。 今回の5の値は欲しい値の最小値です
実際に入れてみました。
console.log(Math.floor(Math.random() * (11 - 5 + 1) + 5)); // 6
console.log(Math.floor(Math.random() * (11 - 5 + 1) + 5)); // 5
console.log(Math.floor(Math.random() * (11 - 5 + 1) + 5)); // 9
ランダムで欲しい値が取れていそうですね!!
min + Math.floor(Math.random() * (max - min + 1))
今までのことを加味して(最大値) - (最小値) +1をMath.random()関数へ掛け算して、その後最小値を足す事でランダムの値を取得できることができるということがわかりました。
普段の業務でcmd+cを使いがちですが、一度余裕を持ってなぜそうなのか考える時間を作ることでさらに成長できる気がします!
最後まで見てくださりありがとうございました!!