JavaScript 逆引き集 | ランダム整数生成

JavaScript JavaScript
スポンサーリンク

JavaScriptランダム整数生成の基本と実践

「0以上n未満のランダムな整数」を作る定番が Math.floor(Math.random() * n)。仕組みを理解すれば、任意の範囲の整数にも応用できます。


基本の考え方

// 0以上 n 未満の整数(0,1,2,...,n-1)
const x = Math.floor(Math.random() * n);
JavaScript
  • Math.random(): 0以上1未満の乱数(例: 0.123…)
  • n倍する: 0以上n未満の小数にスケール
  • Math.floor: 小数点以下を切り捨てて整数に

すぐ使えるテンプレート集

0以上n未満の整数

const n = 6;
const r = Math.floor(Math.random() * n);
console.log(r); // 0〜5のどれか
JavaScript
  • 用途: インデックス選び、配列からランダム要素取得の土台。

1以上n以下の整数(さいころなど)

const n = 6;
const r = Math.floor(Math.random() * n) + 1;
console.log(r); // 1〜6のどれか
JavaScript
  • ポイント: 「+1」で下限を1にずらす。

任意の整数範囲 [min, max](両端含む)

function randInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(randInt(5, 10)); // 5〜10のどれか
JavaScript
  • ポイント: “+1” が両端を「含む」ための鍵。

配列からランダムに1件取る

const items = ["A", "B", "C", "D"];
const pick = items[Math.floor(Math.random() * items.length)];
console.log(pick); // "A"〜"D"のいずれか
JavaScript
  • ポイント: 長さをnとして「0〜n-1」のインデックスを作る。

ランダムに並び替え(シャッフルの簡易版)

const arr = [1, 2, 3, 4, 5];
arr.sort(() => Math.random() - 0.5);
console.log(arr); // なんとなくシャッフル
JavaScript
  • 注意: 厳密な均等シャッフルには Fisher–Yates を使う(下に例)。

均等シャッフル(Fisher–Yates)

function shuffle(a) {
  const arr = [...a];
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1)); // 0〜i
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
  return arr;
}

console.log(shuffle([1,2,3,4,5]));
JavaScript
  • ポイント: すべての並びが同確率になるアルゴリズム。

よくある落とし穴と対策

  • 上端が出ない問題: 1〜nのつもりで Math.floor(Math.random() * n) だけだと「0〜n-1」。上端を含めるには「+1」してから下限をずらす。
  • 範囲式のミス: [min, max] では Math.random() * (max - min + 1) + min+1 を忘れると max が出ない。
  • 非均等シャッフル: sort(() => Math.random() - 0.5) は偏る。公正さが必要なら Fisher–Yates。
  • セキュリティ用途に不適: Math.random は暗号学的に安全ではない。トークンや認証用途には crypto.getRandomValues などを使う。

実務で便利な関数セット

// 0..n-1
const randBelow = n => Math.floor(Math.random() * n);

// [min..max]
const randRange = (min, max) =>
  Math.floor(Math.random() * (max - min + 1)) + min;

// 配列から1つ
const sampleOne = arr => arr[randBelow(arr.length)];
JavaScript
  • 使い分け: インデックスなら randBelow、数値範囲なら randRange、要素抽出なら sampleOne

練習問題(手を動かして覚える)

  • 1. 0〜9の整数を10回出す
for (let i = 0; i < 10; i++) {
  console.log(Math.floor(Math.random() * 10));
}
JavaScript
  • 2. 5〜15の整数を5回出す
for (let i = 0; i < 5; i++) {
  console.log(Math.floor(Math.random() * (15 - 5 + 1)) + 5);
}
JavaScript
  • 3. 配列からランダムに1つ選ぶ
const colors = ["red","blue","green","yellow"];
console.log(colors[Math.floor(Math.random() * colors.length)]);
JavaScript
  • 4. 均等シャッフルして先頭3件を取得
const ids = Array.from({length:10}, (_,i)=>i+1);
const shuffled = shuffle(ids);
console.log(shuffled.slice(0, 3));
JavaScript

直感的な指針

  • 0〜n-1: Math.floor(Math.random() * n)
  • [min, max]を含む: Math.floor(Math.random() * (max - min + 1)) + min
  • ランダム要素: 長さを使ってインデックスを作る。
  • 公正な並び替え: Fisher–Yates。
  • セキュリティは別物: 認証や鍵には Math.random を使わない。

タイトルとURLをコピーしました