From 73056049fea10e15381671e1bc2e592a182d6577 Mon Sep 17 00:00:00 2001 From: Ramtin Jafari Date: Tue, 21 Apr 2026 15:40:44 +0330 Subject: [PATCH] implement intPartitions method in MainExercises --- src/main/java/MainExercises.java | 85 +++++++++++++++++++++----------- 1 file changed, 55 insertions(+), 30 deletions(-) diff --git a/src/main/java/MainExercises.java b/src/main/java/MainExercises.java index c13ad1b..f311c5d 100644 --- a/src/main/java/MainExercises.java +++ b/src/main/java/MainExercises.java @@ -1,3 +1,5 @@ +import java.util.ArrayList; + public class MainExercises { public char[][] generateTriangle(int n) { @@ -61,37 +63,60 @@ public class MainExercises return result; } - /* - integer partitioning is a combinatorics problem in discreet maths - the problem is to generate sum numbers which their summation is the input number - - e.g. 1 -> all partitions of integer 3 are: - 3 - 2, 1 - 1, 1, 1 - - e.g. 2 -> for number 4 goes as: - 4 - 3, 1 - 2, 2 - 2, 1, 1 - 1, 1, 1, 1 - - Note: As you can see in the examples, we want to generate distinct partitions, - which means 1,2 and 2,1 are not different — they count as the same combination. - - You should generate all partitions of the input number. - - Hint: You can determine the size and order of the arrays by finding the pattern - of partitions and their count. Trust me, this one's fun and easy :) - - If you're familiar with Lists and ArrayLists, you can also edit the method's - body to use them instead of arrays. - */ - public int[][] intPartitions(int n) { - // todo - return null; + int[][] result; + ArrayList> mainArray = new ArrayList<>(); + + ArrayList start = new ArrayList<>(); + start.add(n); + mainArray.add(start); + + while (true) { + ArrayList latestArray = mainArray.get(mainArray.size() - 1); + + Integer numberOfInterest = 0; + for (Integer number : latestArray) + { + if (number > 1) { + numberOfInterest = number; + break; + } + } + + if (numberOfInterest == 0) break; + + numberOfInterest--; + Integer remain = n - numberOfInterest; + ArrayList newArray = new ArrayList<>(); + newArray.add(numberOfInterest); + + for (Integer number = numberOfInterest;;) { + if (number >= remain) { + newArray.add(remain); + break; + } + else { + newArray.add(number); + remain -= number; + } + } + + mainArray.add(newArray); + } + + result = new int[mainArray.size()][]; + + for (int i = 0; i < mainArray.size(); i++) { + ArrayList array = mainArray.get(i); + + result[i] = new int[array.size()]; + + for (int j = 0; j < array.size(); j++) { + result[i][j] = array.get(j); + } + } + + return result; }