From d91fc4b93390557f0038385f59e7c0f7f956f8fd Mon Sep 17 00:00:00 2001 From: Amir mohammad Date: Sat, 16 May 2026 11:32:59 +0330 Subject: [PATCH] implement --- src/main/java/MainExercises.java | 94 ++++++++++++++++++++++++++++++-- 1 file changed, 88 insertions(+), 6 deletions(-) diff --git a/src/main/java/MainExercises.java b/src/main/java/MainExercises.java index 21581ea..08a4e08 100644 --- a/src/main/java/MainExercises.java +++ b/src/main/java/MainExercises.java @@ -1,3 +1,5 @@ +import java.util.ArrayList; + public class MainExercises { /* @@ -20,8 +22,24 @@ public class MainExercises */ public char[][] generateTriangle(int n) { - // todo - return null; + char[][] triangle = new char [n][]; + for ( int i = 0; i < n; i++) + { + triangle [i] = new char [i + 1]; + + for ( int j = 0; j <= i; j++) + { + if( i == 0 || j == 0 || i == j || i == n -1) + { + triangle [i][j] = '*'; + } + else + { + triangle [i][j] = ' '; + } + } + } + return triangle; } @@ -58,10 +76,48 @@ public class MainExercises - Number of columns: matrix[0].length (if rectangular) */ public int[] spiralTraversal(int[][] matrix) { - // todo - return null; + + int rows = matrix.length; + int cols = matrix[0].length; + int[] finalmatrix = 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++) { + finalmatrix[index++] = matrix[top][i]; + } + top++; + + for (int i = top; i <= bottom; i++) { + finalmatrix[index++] = matrix[i][right]; + } + right--; + + if (top <= bottom) { + for (int i = right; i >= left; i--) { + finalmatrix[index++] = matrix[bottom][i]; + } + bottom--; + } + + if (left <= right) { + for (int i = bottom; i >= top; i--) { + finalmatrix[index++] = matrix[i][left]; + } + left++; + } + } + + return finalmatrix; } + /* integer partitioning is a combinatorics problem in discreet maths the problem is to generate sum numbers which their summation is the input number @@ -91,10 +147,36 @@ public class MainExercises */ public int[][] intPartitions(int n) { - // todo - return null; + + ArrayList result = new ArrayList<>(); + int[] current = new int[n]; + + + partition(n, n, 0, current, result); + + int[][] output = new int[result.size()][]; + for (int i = 0; i < result.size(); i++) { + output[i] = result.get(i); + } + return output; } + private void partition(int remain, int max, int index, int[] current, ArrayList result) { + if (remain == 0) { + + int[] a = new int[index]; + for (int i = 0; i < index; i++) { + a[i] = current[i]; + } + result.add(a); + return; + } + + for (int next = Math.min(max, remain); next >= 1; next--) { + current[index] = next; + partition(remain - next, next, index + 1, current, result); + } + } public static void main() {