Adding intPartitions object.

This commit is contained in:
2026-04-25 13:44:15 +03:30
parent 9c2990038d
commit b754df02ed
2 changed files with 38 additions and 5 deletions
Generated
+1
View File
@@ -0,0 +1 @@
MainExercises.java
+37 -5
View File
@@ -1,3 +1,5 @@
import java.util.ArrayList;
public class MainExercises
{
/*
@@ -29,6 +31,7 @@ public class MainExercises
triangle[i][j] = ' ';
}
}
return triangle;
}
@@ -124,15 +127,44 @@ public class MainExercises
If you're familiar with Lists and ArrayLists, you can also edit the method's
body to use them instead of arrays.
*/
private ArrayList<ArrayList<Integer>> intPartitionsHelper(int n, int biggest) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
if (n == 0) {
result.add(new ArrayList<>());
return result;
}
for (int k = 1; k <= Math.min(biggest, n); k++) {
ArrayList<ArrayList<Integer>> subPartitions = intPartitionsHelper(n - k, k);
for (ArrayList<Integer> subPartition : subPartitions) {
ArrayList<Integer> newPartition = new ArrayList<>();
newPartition.add(k);
newPartition.addAll(subPartition);
result.add(newPartition);
}
}
return result;
}
public int[][] intPartitions(int n) {
// todo
return null;
ArrayList<ArrayList<Integer>> answerList = intPartitionsHelper(n, n);
int[][] answerArray = new int[answerList.size()][];
for(int i = 0; i < answerList.size(); i++){
answerArray[(answerList.size() - i) - 1] = new int[answerList.get(i).size()];
for(int j = 0; j < answerList.get(i).size(); j++){
answerArray[(answerList.size() - i) - 1][j] = answerList.get(i).get(j);
}
}
return answerArray;
}
public static void main()
public void main()
{
int n = 4;
int[][] partitions = intPartitions(n);
for (int i = 0; i < partitions.length; i++) {
for(int j = 0; j < partitions[i].length; j++)
System.out.print(partitions[i][j]);
System.out.println();
}
}
}