Skip to content

Instantly share code, notes, and snippets.

@Falconerd
Last active January 15, 2016 14:07
Show Gist options
  • Save Falconerd/1c8d0edf4bcbd97cfaf3 to your computer and use it in GitHub Desktop.
Save Falconerd/1c8d0edf4bcbd97cfaf3 to your computer and use it in GitHub Desktop.
Find N partitions of number M with min and max partition size
// 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