- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Splitting number into n parts close to each other in JavaScript
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 −
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 ]
Advertisements