I need help with the ability to divide an unknown integer into a given number of even parts — or at least as even as they can be. The sum of the parts should be the original value, but each part should be an integer, and they should be as close as possible.
Parameters
num: Integer - The number that should be split into equal parts
parts: Integer - The number of parts that the number should be split
into
Return Value
List (of Integers) - A list of parts, with each index representing the part and the number contained within it representing the size of the part. The parts will be ordered from smallest to largest.
this is what I have
var splitInteger = function(num, parts) {
// Complete this function
var randombit = num * parts;
var out = [];
for (var i = 0; i < parts; i++) {
out.push(Math.random());
}
var mult = randombit / out.reduce(function(a, b) {
return a + b;
});
return out.map(function(el) {
return el * mult;
});
}
var d = splitInteger(10, 5)
console.log(d);
console.log("sum - " + d.reduce(function(a, b) {
return a + b
}));
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…