Find N partitions of number M with min and max partition size
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
// Currently, there's a bug when numbers which are too large are used... | |
function getRandomPartitionsFromNumber(number, parts, min, max) { | |
var result = []; | |
for (var i = 0; i < parts; i++) { | |
var part = randomIntFromInterval(min, max); | |
result.push(part); | |
} | |
var sum = result.reduce(add, 0); | |
while (sum !== number) { | |
for (i = 0; i < result.length; i++) { | |
if (sum > number) { | |
if (result[i] > min) { | |
result[i]--; | |
sum--; | |
} | |
} else if (sum < number) { | |
if (result[i] < max) { | |
result[i]++; | |
sum++; | |
} | |
} | |
} | |
} | |
return result; | |
} | |
function randomIntFromInterval(min, max) { | |
return Math.floor(Math.random() * (max - min + 1) + min); | |
} | |
function add(a, b) { | |
return a + b; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment