如何确定谁拥有阵列中奖票?

时间:2017-09-23 10:20:13

标签: javascript arrays

我有票务系统。每个人都有不同的票数。 例如:

person[0] = 50;
person[1] = 75;
person[2] = 81;

0人拥有1-50的门票,

1人拥有51-126的门票,

2人拥有127-208的门票

然后抽签发生,并使用以下公式生成随机票:

totalTickets*(randomProcentage/100)

例如,该公式给了我“52”票作为赢家。我不知道如何找到谁有中奖票。

2 个答案:

答案 0 :(得分:0)

如果所有门票的概率都相同,您可以使用:

Math.floor(Math.random() * numberOfTickets);

结果是中奖彩票。

var tickets = [52, 44, 33];
var index = Math.floor(Math.random() * tickets.length);
var winningTicket = tickets[index];

参考评论。票证数组表示彼此拥有的票数。下面的代码是查找获胜者索引的简单示例:

var tickets = [52, 44, 33];

// Sum the number of tickets
var numberOfTickets = 0;
for (var i = 0; i < tickets.length; i++) {
    numberOfTickets += tickets[i];
}

// Draw random number from 0 ... numberOfTickets
var winningTicket = Math.floor(Math.random() * numberOfTickets);

// Loop the tickets and check if the accumulated sum is higher or equal
// compared to the winning ticket. If it is, then we have our winner
var winner = null;
var accumulativeSum = 0;
for (var i = 0; i < ticket.length; i++) {
    accumulativeSum += ticket[i];
    if (accumulativeSum >= winningTicket) {
        winner = i;
        break;
    }
}

门票:[10,20,30],winsTicket = 5.获胜者= 0

门票:[10,20,30],winsTicket = 11.获胜者= 1

答案 1 :(得分:0)

您可以对票数进行求和并循环,直到总和大于或等于给定值。

&#13;
&#13;
var ticket = [50, 75, 81],
    value = 52,
    index = 0,
    sum = 0;

ticket.some(function (a, i) {
    sum += a;
    index = i;
    return sum >= value;
});
    
console.log(index);
&#13;
&#13;
&#13;