Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Splitting number into n parts close to each other in JavaScript
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 while keeping these conditions in mind:
- The numbers should be as close as possible
- The numbers should be even (if possible)
The ordering of numbers is not important.
Problem Analysis
To split a number into n parts as evenly as possible, we need to:
- Calculate the base quotient using
Math.floor(num / parts) - Find the remainder using
num % parts - Distribute the remainder by adding 1 to some parts
For example, splitting 20 into 6 parts: base = 3, remainder = 2, so we get [3, 3, 3, 3, 4, 4].
Example
Following is the implementation:
const num = 20;
const parts = 6;
const splitNumber = (num = 1, parts = 1) => {
let baseValue = Math.floor(num / parts);
let remainder = num % parts;
const arr = [];
// Fill array with base values
for (let i = 0; i
[ 4, 4, 3, 3, 3, 3 ]
How It Works
The algorithm works by:
- Creating an array filled with the base quotient value
- Adding 1 to the first
remainder elements to distribute the leftover
- This ensures the difference between any two parts is at most 1
Additional Examples
// Example 1: Perfect division
console.log("15 into 3 parts:", splitNumber(15, 3));
// Example 2: With remainder
console.log("10 into 3 parts:", splitNumber(10, 3));
// Example 3: Large remainder
console.log("7 into 4 parts:", splitNumber(7, 4));
15 into 3 parts: [ 5, 5, 5 ]
10 into 3 parts: [ 4, 3, 3 ]
7 into 4 parts: [ 2, 2, 2, 1 ]
Conclusion
This approach efficiently splits any number into n parts with minimal difference between parts. The algorithm ensures optimal distribution by using integer division and remainder distribution.
