weightedRandomSelection method

int weightedRandomSelection(
  1. List<double> distribution,
  2. double randomValue
)

Weighted random selection function

Implementation

int weightedRandomSelection(List<double> distribution, double randomValue) {
  // Step 1: Calculate cumulative sum
  List<double> cumulative = [];
  double total = 0.0;
  for (double weight in distribution) {
    total += weight;
    cumulative.add(total);
  }

  // Step 2: Scale the random value to the range [0, total)
  double target = randomValue * total;

  // Step 3: Find the index where the random value falls
  for (int i = 0; i < cumulative.length; i++) {
    if (target < cumulative[i]) {
      return i;
    }
  }

  // Fallback: Return the last index
  return cumulative.length - 1;
}