Skip to content

Instantly share code, notes, and snippets.

@slimymars
Last active April 7, 2021 11:45
Show Gist options
  • Save slimymars/4b44f7e4e0ceb7a606ee21f84c59623c to your computer and use it in GitHub Desktop.
Save slimymars/4b44f7e4e0ceb7a606ee21f84c59623c to your computer and use it in GitHub Desktop.
// 10000回繰り返し、ランダムの数の出た回数をカウントする
// 1〜maxまでの数のランダムな数を出力する関数
function getRandomInt(max) {
return Math.floor(Math.random() * max + 1);
}
const max = 10; // ランダムの最大値
let d = new Map(); // データカウント用辞書
// 10000回繰り返す
for (let i=0; i<10000; i++) {
let r = getRandomInt(max); // ランダム数取得
// 過去に出ているか
if (d.has(r)) {
// 過去に出た数字であれば1回足す
d.set(r, d.get(r)+1);
} else {
// 過去に出てない数字であれば1で初期化
d.set(r, 1);
}
};
// 数えたデータを出力する
for (let i=1; i<=max; i++) {
console.log(i + ' : ' + d.get(i) + ' 回' );
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment