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++) for (int i = 0; i < n; i++)
{ {
char[] line = new char[i+1]; result[i] = new char[i+1];
if (i == n-1)
if (i == n-1 || i == 0)
{ {
for (int j = 0; j <= i; j++) for (int j = 0; j <= i; j++)
{ {
line[j] = '*'; result[i][j] = '*';
} }
} }
else else
{ {
line[0] = '*'; result[i][0] = '*';
line[i] = '*'; result[i][i] = '*';
for (int j = i - 1; j > 0; j--) { for (int j = 1; j < i; j++) result[i][j] = ' ';
line[j] = ' ';
} }
} }
result[i] = line;
}
return result; return result;
} }
@@ -69,37 +64,61 @@ public class MainExercises
} }
public int[][] intPartitions(int n) { public int[][] intPartitions(int n) {
ArrayList<int[]> result = new ArrayList<>(); int[][] result;
ArrayList<Integer> curPartition = new ArrayList<>(); 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 (numberOfInterest == 0) break;
if (remaining == 0) {
int size = curPartition.size();
int[] savingArr = new int[size];
for (int i = 0; i < size; i++) { numberOfInterest--;
savingArr[i] = curPartition.get(i); 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); mainArray.add(newArray);
return;
} }
for (int i = Math.min(max, remaining); i >= 1; i--) { result = new int[mainArray.size()][];
curPartition.add(i);
int newRemaining = remaining - i;
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() public static void main()
{ {