Skip to content

Instantly share code, notes, and snippets.

@JonathanMonga
Created March 9, 2023 14:11
Show Gist options
  • Save JonathanMonga/2dd4bcee44b0c7597b9754d8e4d57156 to your computer and use it in GitHub Desktop.
Save JonathanMonga/2dd4bcee44b0c7597b9754d8e4d57156 to your computer and use it in GitHub Desktop.
Random integer numbers with fixed sum
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