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)

JavaScript

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:

JavaScript

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:

JavaScript

So I think you should subtract the totalProcessed value instead.

JavaScript

Full working snippet:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement