我有一组问题,并且希望“随机”提出这些问题。一个问题可以被问多次,包括连续问。然而,在提出一个问题之后,再次提出该问题的可能性应该减少,这样,随着问题不断被提出,一个问题被更多人看到的可能性就会变小,并且一个问题的(相对)可能性也会降低。没见过的会上涨。就像所有问题都从 1 开始,然后在被问到之后,可能性为 1/2,然后在第二次之后为 1/3,等等。
这种模式有既定的数据结构/算法吗?
您可以为问题分配权重,并在选择后减小权重:
const arr = Array.from({length:20}, (_, i) => ({title: 'Question ' + (i+1), weight: 1}));
let total = arr.length;
function selectRandom(arr){
const rand = total * Math.random();
let sum = 0;
const found = arr.find(r => (sum += r.weight, rand <= sum));
const diff = found.weight * .5;
total -=diff, found.weight -= diff;
return found;
}
let count=40;
while(count--) console.log(selectRandom(arr));