Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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
}));

This is the sample tests

let assert = require("chai").assert;
describe('Challenge', function() {
  it('Simple Functionality', function() {
    assert.deepEqual(splitInteger(10,1), [10]);
    assert.deepEqual(splitInteger(2,2), [1,1]);
    assert.deepEqual(splitInteger(20,5), [4,4,4,4,4]);
  });
});

Examples of the expected output:

num parts Return Value.

Completely even parts example 10 5 [2,2,2,2,2].

Even as can be parts example 20 6 [3,3,3,3,4,4].

I am getting an error.

like image 737
John Tee Avatar asked May 13 '19 07:05

John Tee


2 Answers

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}));
like image 80
Syed mohamed aladeen Avatar answered Nov 11 '22 03:11

Syed mohamed aladeen


You may get maximum integer coefficient as x/y rounded down to integer and remainder with x%y. Than simply break remainder into 1's and add those 1's to corresponding number of parts:

const breakIntoParts = (num, parts) => 
        [...Array(parts)].map((_,i) => 
          0|num/parts+(i < num%parts))

console.log(JSON.stringify(breakIntoParts(20, 6)));
.as-console-wrapper {min-height: 100%}
like image 37
Yevgen Gorbunkov Avatar answered Nov 11 '22 01:11

Yevgen Gorbunkov