How to divide number n in javascript into x parts, where the sum of all the parts equals the number?

Viewed 9436

I have a number which I need to divide into 5 parts. However, I want each part to be a random number. But when all the parts are added together, they equal the original number. I am unsure of how to do this with JavaScript. Furthermore, I don't want the min of the divided parts to be 0 or 1, I want to set the min myself.

For example, the number is 450. I want the divided parts to be no less than 60. So to start, the array would be [60,60,60,60,60]. But I want to randomize so that they all add up to 450. What would be the best way to go about doing this?

Thank you!

This is what I've tried so far:

let i = 0;
let number = 450;
let numArray = [];
while(i <= 5){
  while(number > 0) {
    let randomNum = Math.round(Math.random() * number) + 1;
    numArray.push(randomNum);
    number -= randomNum;
  }
  i += 1;
}
6 Answers
Related