2 Commits
Author SHA1 Message Date
Ramtin Jafari dd399fd00a implement intPartitions method 2026-06-02 15:25:04 +03:30
Ramtin Jafari 95028697fd fix generateTriangle method 2026-06-02 15:24:39 +03:30
+29 -48
View File
@@ -8,21 +8,26 @@ public class MainExercises
for (int i = 0; i < n; i++) for (int i = 0; i < n; i++)
{ {
result[i] = new char[i+1]; char[] line = 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++)
{ {
result[i][j] = '*'; line[j] = '*';
} }
} }
else else
{ {
result[i][0] = '*'; line[0] = '*';
result[i][i] = '*'; line[i] = '*';
for (int j = 1; j < i; j++) result[i][j] = ' '; for (int j = i - 1; j > 0; j--) {
line[j] = ' ';
}
} }
result[i] = line;
} }
return result; return result;
@@ -64,59 +69,35 @@ public class MainExercises
} }
public int[][] intPartitions(int n) { public int[][] intPartitions(int n) {
int[][] result; ArrayList<int[]> result = new ArrayList<>();
ArrayList<ArrayList<Integer>> mainArray = new ArrayList<>(); ArrayList<Integer> curPartition = new ArrayList<>();
ArrayList<Integer> start = new ArrayList<>(); fillPartition(n, n, curPartition, result);
start.add(n);
mainArray.add(start);
while (true) {
ArrayList<Integer> latestArray = mainArray.get(mainArray.size() - 1);
Integer numberOfInterest = 0; return result.toArray(new int[result.size()][]);
for (Integer number : latestArray) }
{
if (number > 1) {
numberOfInterest = number;
break;
}
}
if (numberOfInterest == 0) 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];
numberOfInterest--; for (int i = 0; i < size; i++) {
Integer remain = n - numberOfInterest; savingArr[i] = curPartition.get(i);
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;
}
} }
mainArray.add(newArray); result.add(savingArr);
return;
} }
result = new int[mainArray.size()][]; for (int i = Math.min(max, remaining); i >= 1; i--) {
curPartition.add(i);
int newRemaining = remaining - i;
for (int i = 0; i < mainArray.size(); i++) { fillPartition(i, newRemaining, curPartition, result);
ArrayList<Integer> array = mainArray.get(i);
result[i] = new int[array.size()]; curPartition.removeLast();
for (int j = 0; j < array.size(); j++) {
result[i][j] = array.get(j);
}
} }
return result;
} }