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

How to add a value randomly to an array using JavaScript

本文关键字:添加 数组 随机 何使用 JavaScript      更新时间:2023-09-26

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

例如,如果我有30头骆驼,我需要在12头骆驼之间分配这个数量。到目前为止,我已经写了下面的代码,但我正在按照要求使用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--;
    }
}

通过添加外循环,您可以正确地添加金额的剩余部分。

while(amount > 0){
    //add amount to camels
}

检查这个Fiddle是否是你想要实现的。