diff --git a/src/main/java/MainExercises.java b/src/main/java/MainExercises.java index 21581ea..d74927c 100644 --- a/src/main/java/MainExercises.java +++ b/src/main/java/MainExercises.java @@ -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> intPartitions(int n) { + ArrayList> result = new ArrayList<>(); + backtrack(n, n, new ArrayList<>(), result); + return result; } + private static void backtrack(int remaining, int max, + ArrayList current, + ArrayList> 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() { }