Main Exercise 2 completed.

This commit is contained in:
2026-04-22 21:12:03 +03:30
parent 2d725cce52
commit 1ee2bb2c26
+47 -2
View File
@@ -1,8 +1,12 @@
import java.util.Arrays;
import java.util.ArrayList;
public class MainExercises public class MainExercises
{ {
public char[][] generateTriangle(int n) { public char[][] generateTriangle(int n) {
char[][] Triangle = new char[n][]; char[][] Triangle = new char[n][];
//The for loop to put the stars a spaces in the array
for(int i=0; i<n; i++) { for(int i=0; i<n; i++) {
Triangle[i] = new char[i+1]; Triangle[i] = new char[i+1];
for (int j = 0; j <= i; j++) { for (int j = 0; j <= i; j++) {
@@ -47,10 +51,51 @@ public class MainExercises
- Number of columns: matrix[0].length (if rectangular) - Number of columns: matrix[0].length (if rectangular)
*/ */
public int[] spiralTraversal(int[][] matrix) { public int[] spiralTraversal(int[][] matrix) {
// todo ArrayList<Integer> result = new ArrayList<>();
return null;
//Setting matrix edge indices
int top = 0;
int bottom = matrix.length - 1;
int left = 0;
int right = matrix[0].length - 1;
//This loop reads the indices in a spiral order and at each stage, it brings the edges closer to the center.
while ((top <= bottom) && (left <= right)) {
for (int i=left; i <= right; i++) {
result.add(matrix[top][i]);
}
top++; //to getting closer to the center
for (int i=top; i <= bottom; i++) {
result.add(matrix[i][right]);
}
right--; //to getting closer to the center
if (top <= bottom) {
for (int i = right; i >= left; i--) {
result.add(matrix[bottom][i]);
}
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) {
result.add(matrix[i][left]);
}
left++;
}
}
int n = (matrix.length)*(matrix[0].length);
int[] finalResult = new int[n]; //for returning an int[] array
for (int i=0; i<n; i++) {
finalResult[i] = result.get(i);
}
return finalResult;
} }
/* /*
integer partitioning is a combinatorics problem in discreet maths integer partitioning is a combinatorics problem in discreet maths
the problem is to generate sum numbers which their summation is the input number the problem is to generate sum numbers which their summation is the input number