implement

This commit is contained in:
2026-05-16 11:32:59 +03:30
parent e73ac6115f
commit d91fc4b933
+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,9 +76,47 @@ 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
@@ -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()
{ {