Splitting number into n parts close to each other in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a number, num, as the first argument and another number, parts, as the second argument.

Our function should split the number num into exactly (parts) numbers and we should keep these two conditions in mind −

  • The numbers should be as close as possible
  • The numbers should even (if possible).

And the ordering of numbers is not important.

For example, if the input to the function is −

Input

const num = 20;
const parts = 6;

Output

const output = [3, 3, 3, 3, 4, 4];

Example

Following is the code −

 Live Demo

const num = 20;
const parts = 6;
const splitNumber = (num = 1, parts = 1) => {
   let n = Math.floor(num / parts);
   const arr = [];
   for (let i = 0; i < parts; i++){
      arr.push(n)
   };
   if(arr.reduce((a, b)=> a + b,0) === num){
      return arr;
   };
   for(let i = 0; i < parts; i++){
      arr[i]++;
      if(arr.reduce((a, b) => a + b, 0) === num){
         return arr;
      };
   };
};
console.log(splitNumber(num, parts));

Output

[ 4, 4, 3, 3, 3, 3 ]
raja
Published on 22-Apr-2021 11:32:10
Advertisements