Skip to content
Advertisement

random number that always makes a total of 100 into array

Hi i am trying to create an array that always has a total of 100 based on random numbers. I get it to work when there is 2 or 3 rows but i can’t get it to work if there are more as 4. Meaning i need to change the middle section. Here is simple code i made: (the length is the number of rows in the array)

var array = []
var length = 3; //4 , 5 , 6 ...
var number;
var calculate;
var totalProcessed;

for (i = 0; i < length; i++) {
  // FIRST ONE
  if(i == 0){
    number = Math.floor(Math.random() * 100) + 1;
    console.log(number);
    totalProcessed = number;
    array.push(number)
  }
  //  MIDDLE SECTION
  if(i > 0 && i == length-1){
    if(length > 2){
      calculate = 100 - number;
      number = Math.floor(Math.random() * calculate) + 1 
      totalProcessed = totalProcessed + number;
      console.log(number);
      array.push(number)
    }
  }
  // LAST ONE
  if(i == length -1){    
    
       var lastOne = 100-totalProcessed;
       console.log(lastOne);
       array.push(lastOne)
    
  }
}
console.log(array);

How should i change the middle section to be able to capture the numbers?

Advertisement

Answer

There are two errors in this code:

First:

You should change the == to < in order to be able to loop more then 3 times:

if(i > 0 && i == length-1)

Second:

I think your error occurs on the following line. You subtract number from 100 which is the previous generated number. You should instead generate a random number from everything that is left:

calculate = 100 - number;

So I think you should subtract the totalProcessed value instead.

calculate = 100 - totalProcessed;

Full working snippet:

var array = []
var length = 5; //4 , 5 , 6 ...
var number;
var calculate;
var totalProcessed;

for (i = 0; i < length; i++) {
  // FIRST ONE
  if(i == 0){
    number = Math.floor(Math.random() * 100) + 1;
    console.log(number);
    totalProcessed = number;
    array.push(number)
  }
  //  MIDDLE SECTION
  if(i > 0 && i < length-1){
    if(length > 2){
      calculate = 100 - totalProcessed;
      number = Math.floor(Math.random() * calculate) + 1 
      totalProcessed = totalProcessed + number;
      console.log(number);
      array.push(number)
    }
  }
  // LAST ONE
  if(i == length -1){    
    
       var lastOne = 100-totalProcessed;
       console.log(lastOne);
       array.push(lastOne)
    
  }
}
console.log(array);

let total = 0;
array.forEach(el => total += el)
console.log(total)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement