How to add random value to array using JavaScript

I am new to JavaScript, and I move on to the task when I have to randomly distribute an input value between 12 loads. The other side is that each element of the array cannot differ from the next by more than one.

so, for example, if I have 30, I need to distribute this amount between 12 camels. I still wrote the code below, but I am using TextPad on request. I am not sure how to print the result on the same line.

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)
}

comment if you need more information, thanks

+4
source share
2 answers

. , , , , , , .. .

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--;
    }
}

Update

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--;
    }
}
+2

, .

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

, Fiddle - , .

0

All Articles