implement main exercises

This commit is contained in:
Fatemesadat Mirabootalebi
2026-04-20 12:58:52 -07:00
parent e73ac6115f
commit 6487f2e0c8
2 changed files with 152 additions and 8 deletions
+83 -6
View File
@@ -1,3 +1,6 @@
import java.util.ArrayList;
import java.util.List;
public class MainExercises
{
/*
@@ -19,10 +22,24 @@ public class MainExercises
the output has to be a two-dimensional array of characters, so don't just print the triangle!
*/
public char[][] generateTriangle(int n) {
if ( n == 0){
return new char[0][];
}
// todo
return null;
char [][] triangle = new char[n][];
for (int x = 0; x < n; x++){
triangle[x] = new char[x + 1];
for (int y = 0; y <= x; y++){
if (y == 0 || x == y || x == n-1){
triangle[x][y] = '*';
}
else {
triangle[x][y] = ' ';
}
}
}
return triangle;
}
@@ -58,8 +75,43 @@ public class MainExercises
- Number of columns: matrix[0].length (if rectangular)
*/
public int[] spiralTraversal(int[][] matrix) {
// todo
return null;
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return new int[0];
}
int[] path = new int[matrix.length * matrix[0].length];
int up = 0 ;
int down = matrix.length - 1;
int left = 0;
int right = matrix[0].length - 1;
int step = 0;
while ( up <= down && left <= right){
for (int i = left; i <= right; i++){
path[step++] = matrix[up][i];
}
up++;
for (int j = up; j <= down; j++){
path[step++] = matrix[j][right];
}
right--;
if (up <= down){
for (int i = right; i >=left; i--){
path[step++] = matrix[down][i];
}
down--;
}
if (right >= left){
for (int j = down; j >= up; j--){
path[step++] = matrix[j][left];
}
left++;
}
}
return path;
}
/*
@@ -89,10 +141,35 @@ 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.
*/
//Helper method
private void makePartitions(int remain, int max, List<Integer> current, List<int[]> result){
if (remain == 0){
int[] arr = new int[current.size()];
for (int i = 0; i < current.size(); i++){
arr[i] = current.get(i);
}
result.add(arr);
return;
}
for(int i = Math.min(max, remain); i >= 1; i--){
current.add(i);
makePartitions(remain - i, i, current, result);
current.remove(current.size() - 1);
}
}
public int[][] intPartitions(int n) {
// todo
return null;
List<int[]> result = new ArrayList<>();
List<Integer> current = new ArrayList<>();
makePartitions(n, n, current, result);
int[][] output = new int[result.size()][];
for (int i = 0; i < result.size(); i++){
output[i] = result.get(i);
}
return output;
}