gpt4 book ai didi

javascript - 如何使用 JavaScript 将值随机添加到数组

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:16:56 24 4
gpt4 key购买 nike

我是 JavaScript 的新手,我正在执行一项任务,我必须在 12 个负载之间随机分散输入值。另一方面是数组的每个元素与下一个元素的差异不能超过一个。

例如,如果我有 30 头 Camel ,我需要将此数量分配给 12 头 Camel 。到目前为止,我已经编写了下面的代码,但我正在按照要求使用 TextPad,我不确定如何在同一行上打印出结果。

var amount = 30;

var camels = [0,0,0,0,0,0,0,0,0,0,0,0]

var div = amount/12;

var mod = amount%12;

var x = mod / 12;


for(i=0;i<camels.length;i++){
WScript.echo(camels[i] + "|" + Math.floor(div) + "|" + mod + "|" + x)
}

如果您需要更多信息,请发表评论,谢谢

最佳答案

这是我的看法。请注意,对于声明数组值不能与下一个值相差超过一个的要求,我认为数组是循环的,即最后一个值之后的值再次成为第一个值。

var amount = 30;
var camels = [0,0,0,0,0,0,0,0,0,0,0,0];

while (amount > 0) {
var index = Math.floor(Math.random() * camels.length);
var previous = (camels.length + index - 1) % camels.length;
var next = (index + 1) % camels.length;

if (Math.abs(camels[index] + 1 - camels[previous]) <= 1
&& Math.abs(camels[index] + 1 - camels[next]) <= 1) {

camels[index]++;
amount--;
}
}

更新

应 OP 的要求,这是一个带注释的版本:

// the amount that needs to be distributed among the camels
var amount = 30;

// the actual values for all 12 camels, initially all zero
var camels = [0,0,0,0,0,0,0,0,0,0,0,0];

// as long as we have something to distribute
while (amount > 0) {

// get a random current index in the array, i.e. a value between 0 and 11
var index = Math.floor(Math.random() * camels.length);

// calculate the index previous to the current index;
// in case the current index is 0, the previous index will be 11
var previous = (camels.length + index - 1) % camels.length;

// calculate the index next to the current index;
// in case the current index is 11, the next index will be 0
var next = (index + 1) % camels.length;

// if adding 1 to the camel at the current index makes it so that
// the difference with the camel at the previous index is 1 or lower
// the difference with the camel at the next index is 1 or lower
if (Math.abs(camels[index] + 1 - camels[previous]) <= 1
&& Math.abs(camels[index] + 1 - camels[next]) <= 1) {

// go ahead and add 1 to that camel
camels[index]++;

// and decrement the amount accordingly
amount--;
}
}

关于javascript - 如何使用 JavaScript 将值随机添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26883815/

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