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.

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  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
Updated on: 2020-12-11T09:20:28+05:30

811 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements