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
+44 -35
View File
@@ -1,23 +1,33 @@
import java.util.ArrayList;
public class MainExercises public class MainExercises
{ {
public char[][] generateTriangle(int n) { public char[][] generateTriangle(int n) {
char[][] result = new char[n][n]; char[][] result = new char[n][];
for (int i = 0; i < n; i++) for (int i = 0; i < n; i++)
{ {
if (i == n-1) char[] line = new char[i+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 = i - 1; j > 0; j--) {
line[j] = ' ';
}
} }
result[i] = line;
} }
return result; return result;
@@ -58,37 +68,36 @@ public class MainExercises
return result; 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) { public int[][] intPartitions(int n) {
// todo ArrayList<int[]> result = new ArrayList<>();
return null; ArrayList<Integer> curPartition = new ArrayList<>();
fillPartition(n, n, curPartition, result);
return result.toArray(new int[result.size()][]);
}
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];
for (int i = 0; i < size; i++) {
savingArr[i] = curPartition.get(i);
}
result.add(savingArr);
return;
}
for (int i = Math.min(max, remaining); i >= 1; i--) {
curPartition.add(i);
int newRemaining = remaining - i;
fillPartition(i, newRemaining, curPartition, result);
curPartition.removeLast();
}
} }