I saw several solutions in python and java here but I didn't find anything using javascript. How do I generate 5 random numbers whose sum is equal to 100?
// output: {10, 20, 50, 10, 10}
CodePudding user response:
let sum = 100
const numbers = []
for (let i = 0; i < 4; i ) {
const randomNumber = Math.floor(Math.random() * sum)
sum -= randomNumber < 0 ? 0 : randomNumber
numbers.push(randomNumber < 0 ? 0 : randomNumber)
}
numbers.push(sum)
console.log(numbers, numbers.reduce((a, b) => a b, 0)) // 5 random numbers of sum 100