Created
March 9, 2023 14:11
-
-
Save JonathanMonga/2dd4bcee44b0c7597b9754d8e4d57156 to your computer and use it in GitHub Desktop.
Random integer numbers with fixed sum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function arraySum(a) { | |
return a.reduce((a, b) => a + b, 0) | |
} | |
function getRandomIntInclusive(min, max) { | |
const minCeil = Math.ceil(min) | |
const maxFloor = Math.floor(max) | |
return Math.floor(Math.random() * (maxFloor - minCeil + 1)) + minCeil | |
} | |
function randomNumbersWithFixedSum(quantity, sum) { | |
const randoms = [...Array(quantity - 1).keys()].map(q => getRandomIntInclusive(0, sum/quantity)) | |
const last = sum - arraySum(randoms) | |
return [...randoms, last] | |
} | |
console.log(randomNumbersWithFixedSum(1, 100)) | |
console.log(randomNumbersWithFixedSum(2, 100)) | |
console.log(randomNumbersWithFixedSum(3, 100)) | |
console.log(randomNumbersWithFixedSum(4, 100)) | |
console.log(randomNumbersWithFixedSum(5, 100)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment