gpt4 book ai didi

模拟现场投票的算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:19:47 24 4
gpt4 key购买 nike

我想编写一个算法来模拟现场投票。

观众有 4 个不同的选项可以投票。我可视化每个选项 a、b、c、d 的百分比。

所以我想出了一个算法,可以给我一个由 4 个随机数组成的数组,总和为 100。

dataset = [];
a = randombetween(0, max);
b = randombetween(0, max - a);
c = randombetween(0, max - a - b);
d = max - a - b - c;
dataset.push(a, b, c, d);
shuffle(dataset);

此代码每 2 秒执行一次以更新轮询结果。

为了使我的算法更加逼真,我希望更改更加渐进。我想创建一个初始随机结果,然后逐渐增加/减少投票结果。假设投票结果每次更新增加/减少不应超过 5%。

这里有一个可以玩的 fiddle :Live Poll

最佳答案

为什么不模拟提交投票的恒定比率?这样,当你计算百分比时,当有更多人投票时,变化会更小。这似乎比更改百分比更有效。我把它放在一起作为演示 (https://jsfiddle.net/ovkfw577/1/)

var votes = [0,0,0,0];
var dataset = [0,0,0,0];
var dataSize = 4;
var voteRate = 10;

// Algorithm to simulate the further voting process
var updateData = function() {

var total = 0;
dataset = [0,0,0,0];

// add random amount of votes
for(i=0; i < dataSize; i++) {
var randomVotes = randombetween(0,voteRate);
votes[i] += randomVotes;
total += votes[i];
}

// calculate percentages
for(i=0; i < dataSize; i++) {
dataset[i] = votes[i] / total * 100;
}

// so poll bars don't completely stall later on.
// not entirely necessary, but helps polling
// appear more active.
voteRate *= 1.2;

drawVis();
$("svg").fadeIn("slow");
};

关于模拟现场投票的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35366599/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com