Finding all possible ways of integer partitioning in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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.

Example

Following is the code −

const findPartitions = (num = 1) => {
   const arr = Array(num + 1).fill(null).map(() => {
      return Array(num + 1).fill(null);
   });
   for (let j = 1; j <= num; j += 1) {
      arr[0][j] = 0;
   }
   for (let i = 0; i <= num; i += 1) {
      arr[i][0] = 1;
   }
   for (let i = 1; i <= num; i += 1) {
      for (let j = 1; j <= num; j += 1) {
         if (i > j) {
            arr[i][j] = arr[i - 1][j];
         }
         else {
            const exclusive = arr[i - 1][j];
            const inclusive = arr[i][j - i];
            arr[i][j] = exclusive + inclusive;
         }
      }
   }
   return arr[num][num];
};
console.log(findPartitions(4));

Output

Following is the output on console −

5
raja
Published on 11-Dec-2020 09:19:59
Advertisements