2 Commits
Author SHA1 Message Date
Ramtin 73056049fe implement intPartitions method in MainExercises 2026-04-21 15:40:44 +03:30
Ramtin cb480fe4e2 fix generateTriangle method logical bug 2026-04-21 14:40:14 +03:30
+47 -28
View File
@@ -8,28 +8,23 @@ public class MainExercises
for (int i = 0; i < n; i++)
{
char[] line = new char[i+1];
if (i == n-1 || i == 0)
result[i] = new char[i+1];
if (i == n-1)
{
for (int j = 0; j <= i; j++)
{
line[j] = '*';
result[i][j] = '*';
}
}
else
{
line[0] = '*';
line[i] = '*';
result[i][0] = '*';
result[i][i] = '*';
for (int j = i - 1; j > 0; j--) {
line[j] = ' ';
for (int j = 1; j < i; j++) result[i][j] = ' ';
}
}
result[i] = line;
}
return result;
}
@@ -69,37 +64,61 @@ public class MainExercises
}
public int[][] intPartitions(int n) {
ArrayList<int[]> result = new ArrayList<>();
ArrayList<Integer> curPartition = new ArrayList<>();
int[][] result;
ArrayList<ArrayList<Integer>> mainArray = new ArrayList<>();
fillPartition(n, n, curPartition, result);
ArrayList<Integer> start = new ArrayList<>();
start.add(n);
mainArray.add(start);
return result.toArray(new int[result.size()][]);
while (true) {
ArrayList<Integer> latestArray = mainArray.get(mainArray.size() - 1);
Integer numberOfInterest = 0;
for (Integer number : latestArray)
{
if (number > 1) {
numberOfInterest = number;
break;
}
}
private void fillPartition(int max, int remaining, ArrayList<Integer> curPartition, ArrayList<int[]> result) {
if (remaining == 0) {
int size = curPartition.size();
int[] savingArr = new int[size];
if (numberOfInterest == 0) break;
for (int i = 0; i < size; i++) {
savingArr[i] = curPartition.get(i);
numberOfInterest--;
Integer remain = n - numberOfInterest;
ArrayList<Integer> newArray = new ArrayList<>();
newArray.add(numberOfInterest);
for (Integer number = numberOfInterest;;) {
if (number >= remain) {
newArray.add(remain);
break;
}
else {
newArray.add(number);
remain -= number;
}
}
result.add(savingArr);
return;
mainArray.add(newArray);
}
for (int i = Math.min(max, remaining); i >= 1; i--) {
curPartition.add(i);
int newRemaining = remaining - i;
result = new int[mainArray.size()][];
fillPartition(i, newRemaining, curPartition, result);
for (int i = 0; i < mainArray.size(); i++) {
ArrayList<Integer> array = mainArray.get(i);
curPartition.removeLast();
result[i] = new int[array.size()];
for (int j = 0; j < array.size(); j++) {
result[i][j] = array.get(j);
}
}
return result;
}
public static void main()
{