From bcb5363442fe593bb062caec69e03ff0b8597a4f Mon Sep 17 00:00:00 2001 From: kasra Date: Tue, 9 Jun 2026 18:23:19 +0330 Subject: [PATCH] Implement all main exercises --- .idea/misc.xml | 2 +- pom.xml | 4 +- src/main/java/MainExercises.java | 71 ++++++++++++++++++++++++++------ 3 files changed, 62 insertions(+), 15 deletions(-) diff --git a/.idea/misc.xml b/.idea/misc.xml index d2b5d0f..6d8c48b 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -8,7 +8,7 @@ - + \ No newline at end of file diff --git a/pom.xml b/pom.xml index d469778..e8faa3a 100644 --- a/pom.xml +++ b/pom.xml @@ -9,8 +9,8 @@ 1.0-SNAPSHOT - 25 - 25 + 17 + 17 UTF-8 diff --git a/src/main/java/MainExercises.java b/src/main/java/MainExercises.java index 21581ea..f6bf382 100644 --- a/src/main/java/MainExercises.java +++ b/src/main/java/MainExercises.java @@ -1,3 +1,7 @@ +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + public class MainExercises { /* @@ -19,10 +23,16 @@ 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) { - - // todo - return null; - + char[][] tr = new char[n][]; + for (int i = 0; i < n; i++) { + tr[i] = new char[i + 1]; + for (int j = 0; j <= i; j++) + if (j == 0 || i == n - 1 || j == i) + tr[i][j] = '*'; + else + tr[i][j] = ' '; + } + return tr; } @@ -58,8 +68,30 @@ 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) + return new int[0]; + int rw = matrix.length, cl = matrix[0].length; + int[] res = new int[rw * cl]; + int tp = 0, bt = rw - 1, l = 0, r = cl - 1, idx = 0; + while (tp <= bt && l <= r) { + for (int i = tp; i <= r; i++) + res[idx++] = matrix[tp][i]; + tp++; + for (int i = tp; i <= bt; i++) + res[idx++] = matrix[i][r]; + r--; + if (tp <= bt) { + for (int i = r; i >= l; i--) + res[idx++] = matrix[bt][i]; + bt--; + } + if (l <= r) { + for (int i = bt; i >= tp; i--) + res[idx++] = matrix[i][l]; + l++; + } + } + return res; } /* @@ -91,13 +123,28 @@ public class MainExercises */ public int[][] intPartitions(int n) { - // todo - return null; + List> res = new ArrayList<>(); + f(n, n, new ArrayList<>(), res); + int[][] a = new int[res.size()][]; + for (int i = 0; i < res.size(); i++) { + List r = res.get(i); + a[i] = new int[r.size()]; + for (int j = 0; j < r.size(); j++) a[i][j] = r.get(j); + } + return a; + } + private void f(int t, int m, List curr, List> res) { + if (t == 0) { + res.add(new ArrayList<>(curr)); + return; + } + for (int i = Math.min(t, m); i >= 1; i--) { + curr.add(i); + f(t - i, i, curr, res); + curr.remove(curr.size() - 1); + } } - - public static void main() - { - + public static void main() { } } \ No newline at end of file -- 2.54.0