如何使用JavaScript随机向数组添加值

我是
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--;
    }
}
点赞