Merge pull request 'implement triangle method' (#1) from develop into main

Reviewed-on: #1

100/100
This commit was merged in pull request #1.
This commit is contained in:
2026-06-12 13:27:46 +00:00
+88 -6
View File
@@ -1,3 +1,5 @@
import java.util.ArrayList;
public class MainExercises public class MainExercises
{ {
/* /*
@@ -20,8 +22,24 @@ public class MainExercises
*/ */
public char[][] generateTriangle(int n) { public char[][] generateTriangle(int n) {
// todo char[][] triangle = new char [n][];
return null; 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) - Number of columns: matrix[0].length (if rectangular)
*/ */
public int[] spiralTraversal(int[][] matrix) { 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 integer partitioning is a combinatorics problem in discreet maths
the problem is to generate sum numbers which their summation is the input number 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) { public int[][] intPartitions(int n) {
// todo
return null; ArrayList<int[]> 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<int[]> 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() public static void main()
{ {