From 1ee2bb2c26b0adc6c0d6ee796ec0284aa01a0a7b Mon Sep 17 00:00:00 2001 From: Zahra Gharagozloo Mazlaghan Date: Wed, 22 Apr 2026 21:12:03 +0330 Subject: [PATCH] Main Exercise 2 completed. --- src/main/java/MainExercises.java | 49 ++++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/src/main/java/MainExercises.java b/src/main/java/MainExercises.java index a8fd7fb..a70f990 100644 --- a/src/main/java/MainExercises.java +++ b/src/main/java/MainExercises.java @@ -1,8 +1,12 @@ +import java.util.Arrays; +import java.util.ArrayList; + public class MainExercises { public char[][] generateTriangle(int n) { char[][] Triangle = new char[n][]; + //The for loop to put the stars a spaces in the array for(int i=0; i result = new ArrayList<>(); + + //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