Implement all main exercises

This commit is contained in:
2026-06-09 18:23:19 +03:30
parent e73ac6115f
commit bcb5363442
3 changed files with 62 additions and 15 deletions
+1 -1
View File
@@ -8,7 +8,7 @@
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="25" project-jdk-type="JavaSDK">
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" project-jdk-name="25" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
+2 -2
View File
@@ -9,8 +9,8 @@
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>25</maven.compiler.source>
<maven.compiler.target>25</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
+59 -12
View File
@@ -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<List<Integer>> res = new ArrayList<>();
f(n, n, new ArrayList<>(), res);
int[][] a = new int[res.size()][];
for (int i = 0; i < res.size(); i++) {
List<Integer> 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<Integer> curr, List<List<Integer>> 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() {
}
}