diff --git a/README.md b/README.md index fe69c30..b3d47e8 100644 --- a/README.md +++ b/README.md @@ -110,6 +110,7 @@ public int[][] intPartitions(int n); **Task 3: Make all tests pass** - Run the tests frequently as you implement each method +- - Each test file under `test/java` should execute without failures **Project structure reference:** diff --git a/src/main/java/MainExercises.java b/src/main/java/MainExercises.java index 21581ea..a201120 100644 --- a/src/main/java/MainExercises.java +++ b/src/main/java/MainExercises.java @@ -1,3 +1,5 @@ +import java.util.ArrayList; + public class MainExercises { /* @@ -18,10 +20,29 @@ 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) { + public static char[][] generateTriangle(int n) { // todo - return null; + int i; + int j; + char [][] g = new char[i][j]; + + for (i = 1; i <= n; i++) + { + for (j = 1; j <= i; j++) + { + if (j == 1 || j == i) + { + g[i][j] = '*'; + } + else + { + g[i][j] = ' '; + } + } + } + + return g; } @@ -59,6 +80,7 @@ public class MainExercises */ public int[] spiralTraversal(int[][] matrix) { // todo + return null; } @@ -92,12 +114,45 @@ public class MainExercises public int[][] intPartitions(int n) { // todo - return null; + ArrayList> allP = new ArrayList<>(); + ArrayList cPartition = new ArrayList<>(); + + gPartitions(n, n, allP, cPartition); + + int[][] result = new int[allP.size()][]; + for (int i = 0; i < allP.size(); i++) { + ArrayList partition = allP.get(i); + result[i] = new int[partition.size()]; + for (int j = 0; j < partition.size(); j++) { + result[i][j] = partition.get(j); + } + } + return result; } + private void gPartitions(int rSum, int maxV, ArrayList> allPartitions, ArrayList partition) { + + if (rSum == 0) { + allPartitions.add(new ArrayList<>(partition)); + return; + } + if (rSum < 0) { + return; + } + for (int i = Math.min(rSum, maxV); i >= 1; i--) { + partition.add(i); + + gPartitions(rSum - i, i, allPartitions, partition); + + partition.remove(partition.size() - 1); + } + + } public static void main() { + generateTriangle(6); + intPartitions(5); } } \ No newline at end of file