Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

javascript - How to divide an unknown integer into a given number of (almost) even integers

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try like this.

var splitInteger = function(num, parts) {
  // Complete this function

  var val;
  var mod = num % parts;
  if(mod == 0){
    val = num/parts;
    retData = Array(parts).fill(val);
  } else {
    val = (num-mod)/parts;
    retData = Array(parts).fill(val);
    for(i=0;i<mod;i++){
      retData[i] = retData[i] + 1;
    }
    retData.reverse()
  }

  return retData;

}
var d = splitInteger(20, 6)
console.log(d);
console.log("sum - " + d.reduce(function(a,b){return a+b}));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...