Generate random numbers with weighted ranges

by slawe

JavaScript

// generate random variable numbers within range and multiple percentage chance
function generateRandomVariables(weightedRanges, count) {
  const results = [];

  for (let i = 0; i < count; i++) {
    const roll = Math.random() * 100;
    let cumulative = 0;
    let value = null;

    for (const { min, max, chance } of weightedRanges) {
      cumulative += chance;
      if (roll <= cumulative) {
        value = Math.floor(Math.random() * (max - min) + min);
        break;
      }
    }

    results.push(value); // may be null if total chance < 100
  }

  return results;
}

const ranges = [
  { min: 1, max: 60, chance: 60 },
  { min: 61, max: 90, chance: 30 },
  { min: 91, max: 100, chance: 10 }
];

const numbers = generateRandomVariables(ranges, 5);

console.log(numbers);