Maison >interface Web >js tutoriel >Comment la génération de nombres aléatoires pondérés peut-elle être optimisée pour plus d'efficacité ?
Generate Weighted Random Numbers
Weighted random number generation involves selecting a random number from a range where the probability of each number is determined by a weight. This task arises in various applications, such as simulations and games.
Initial Solution
A common approach is rejection sampling, as exemplified in the provided ColdFusion code. This method involves creating a lookup table with elements distributed according to their weights. However, this approach has limitations, such as linear overhead in building the table and potential memory consumption issues.
Alternative Strategies
Implementation
An implementation of weighted random number generation in JavaScript using alias sampling:
function weightedRand(weights) { // Build the alias table let table = []; let totalWeight = 0; for (let i = 0; i < weights.length; i++) { totalWeight += weights[i]; } for (let i = 0; i < weights.length; i++) { let prob = weights[i] / totalWeight; let alias = i; table.push({ prob: prob, alias: alias }); } // Generate a random number return function() { let r = Math.random() * totalWeight; let i = 0; let alias = -1; while (i < table.length && alias === -1) { if (r < table[i].prob) { alias = i; } else { r -= table[i].prob; i = table[i].alias; } } return alias; } }
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!