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
Finding all possible ways of integer partitioning in JavaScript
The partition of a positive integer n is a way of writing n as a sum of positive integers. Two sums that differ only in the order of their summands are considered the same partition.
For example, 4 can be partitioned in five distinct ways:
4 3 + 1 2 + 2 2 + 1 + 1 1 + 1 + 1 + 1
We are required to write a JavaScript function that takes in a positive integer as the only argument. The function should find and return all the possible ways of partitioning that integer.
How It Works
The algorithm uses dynamic programming to count partitions. It creates a 2D array where arr[i][j] represents the number of ways to partition j using integers from 1 to i.
Example: Counting Partitions
const findPartitions = (num = 1) => {
const arr = Array(num + 1).fill(null).map(() => {
return Array(num + 1).fill(null);
});
// Initialize base cases
for (let j = 1; j <= num; j += 1) {
arr[0][j] = 0; // No partitions with 0 parts
}
for (let i = 0; i <= num; i += 1) {
arr[i][0] = 1; // One way to partition 0 (empty partition)
}
// Fill the DP table
for (let i = 1; i <= num; i += 1) {
for (let j = 1; j <= num; j += 1) {
if (i > j) {
// Cannot use number i to partition j (i > j)
arr[i][j] = arr[i - 1][j];
} else {
const exclusive = arr[i - 1][j]; // Don't use i
const inclusive = arr[i][j - i]; // Use i at least once
arr[i][j] = exclusive + inclusive;
}
}
}
return arr[num][num];
};
console.log(findPartitions(4));
console.log(findPartitions(5));
console.log(findPartitions(6));
5 7 11
Example: Getting Actual Partitions
To get the actual partition combinations instead of just the count:
const getAllPartitions = (n, max = n, current = []) => {
if (n === 0) {
return [current.slice()]; // Found a valid partition
}
const partitions = [];
for (let i = Math.min(max, n); i >= 1; i--) {
current.push(i);
partitions.push(...getAllPartitions(n - i, i, current));
current.pop();
}
return partitions;
};
console.log("Partitions of 4:");
console.log(getAllPartitions(4));
console.log("\nPartitions of 5:");
console.log(getAllPartitions(5));
Partitions of 4: [ [ 4 ], [ 3, 1 ], [ 2, 2 ], [ 2, 1, 1 ], [ 1, 1, 1, 1 ] ] Partitions of 5: [ [ 5 ], [ 4, 1 ], [ 3, 2 ], [ 3, 1, 1 ], [ 2, 2, 1 ], [ 2, 1, 1, 1 ], [ 1, 1, 1, 1, 1 ] ]
Comparison
| Approach | Time Complexity | Space Complexity | Output |
|---|---|---|---|
| Dynamic Programming | O(n²) | O(n²) | Count only |
| Recursive Backtracking | O(2^n) | O(n) | All partitions |
Conclusion
Integer partitioning can be solved efficiently using dynamic programming for counting, or recursively for generating all partitions. The DP approach is faster for large numbers when only the count is needed.
