"Complete assignment - ready for grading" #1

Merged
reyhne merged 2 commits from develop into main 2026-07-16 18:01:48 +00:00
Showing only changes of commit 250bfe6361 - Show all commits
+85 -6
View File
@@ -1,3 +1,5 @@
import java.util.ArrayList;
public class MainExercises
{
/*
@@ -21,7 +23,26 @@ public class MainExercises
public char[][] generateTriangle(int n) {
// todo
return null;
char[][] triangle = new char[n][];
for (int i = 0; i < n; i++) {
if (i == 0) {
triangle[0][0] = '*';
}
else if (i < (n - 1) && i > 0) {
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
triangle[i][j] = '*';
}
else triangle[i][j] = ' ';
}
}
else if (i == (n - 1)) {
for (int k = 0; k < n; k++) {
triangle[i][k] = '*';
}
}
}
return triangle;
}
@@ -59,7 +80,49 @@ public class MainExercises
*/
public int[] spiralTraversal(int[][] matrix) {
// todo
return null;
if (matrix == null || matrix.length == 0) {
return new int[0];
}
int rows = matrix.length;
int cols = matrix[0].length;
int[] result = new int[rows * cols];
int index = 0;
int top = 0;
int bottom = rows - 1;
int left = 0;
int right = cols - 1;
while (top <= bottom && left <= right) {
for (int i = left; i <= right; i++) {
result[index++] = matrix[top][i];
}
top++;
for (int i = top; i <= bottom; i++) {
result[index++] = matrix[i][right];
}
right--;
if (top <= bottom) {
for (int i = right; i >= left; i--) {
result[index++] = matrix[bottom][i];
}
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) {
result[index++] = matrix[i][left];
}
left++;
}
}
return result;
}
/*
@@ -90,13 +153,29 @@ public class MainExercises
body to use them instead of arrays.
*/
public int[][] intPartitions(int n) {
// todo
return null;
public static ArrayList<ArrayList<Integer>> intPartitions(int n) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
backtrack(n, n, new ArrayList<>(), result);
return result;
}
private static void backtrack(int remaining, int max,
ArrayList<Integer> current,
ArrayList<ArrayList<Integer>> result) {
public static void main()
if (remaining == 0) {
result.add(new ArrayList<>(current));
return;
}
for (int i = Math.min(max, remaining); i >= 1; i--) {
current.add(i);
backtrack(remaining - i, i, current, result);
current.remove(current.size() - 1); // backtrack
}
}
static void main()
{
}