0以上1未満のランダムな浮動小数点数を返す
// ── 基本: 0以上1未満のランダムな小数 ────────────────────
console.log(Math.random()); // 例: 0.7394... (毎回異なる)
// ── 整数の乱数を作る ─────────────────────────────────
// 1〜6のランダム整数(サイコロ)
const dice = Math.floor(Math.random() * 6) + 1;
console.log(dice); // 1〜6のどれか
// ── 汎用的な範囲指定の乱数関数 ─────────────────────
function randomInt(min: number, max: number): number {
// min 以上 max 以下の整数を返す
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 100)); // 1〜100のランダム整数
console.log(randomInt(10, 20)); // 10〜20のランダム整数
// ── 配列からランダムに1つ選ぶ ─────────────────────────
const options = ['岩', 'はさみ', 'かみ'];
const random = options[Math.floor(Math.random() * options.length)];
console.log(random); // ランダムに1つ選ばれる暗号学的に安全な乱数には crypto.getRandomValues()を使う。Math.random()は予測可能なため認証用途には不向き。