Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript generate 5 random numbers whose sum is equal to 100

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}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading