3 Commits
Author SHA1 Message Date
Fateme_Azizi c287af8aae implement intPartitions method 2026-04-23 04:13:00 +03:30
Fateme_Azizi b8b9b6f482 implement spiralTraversal method 2026-04-21 22:37:05 +03:30
Fateme_Azizi f52a3d29d9 implement generateTriangle method 2026-04-21 20:19:48 +03:30
+107 -6
View File
@@ -1,3 +1,5 @@
import java.util.ArrayList;
public class MainExercises public class MainExercises
{ {
/* /*
@@ -20,9 +22,20 @@ 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 (j == 0 || j == i || i == n-1)
triangle[i][j] = '*';
else
triangle[i][j] = ' ';
}
}
return triangle;
} }
@@ -58,8 +71,50 @@ 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 columns = matrix[0].length;
int[] result = new int[rows*columns];
int count = 0;
int top = 0;
int bottom = rows - 1;
int right = columns - 1;
int left = 0;
while (top <= bottom && left <= right) {
for(int j = left ; j<=right ; j++) {
result[count] = matrix[top][j];
count++;
}
top++;
for(int i = top ; i<=bottom ; i++) {
result[count] = matrix[i][right];
count++;
}
right--;
if(top <= bottom) {
for (int j = right; j >= left; j--) {
result[count] = matrix[bottom][j];
count++;
}
}
bottom--;
if(left <= right){
for (int i = bottom; i >= top; i--) {
result[count] = matrix[i][left];
count++;
}
}
left++;
}
return result;
} }
/* /*
@@ -91,10 +146,56 @@ public class MainExercises
*/ */
public int[][] intPartitions(int n) { public int[][] intPartitions(int n) {
// todo
return null;
ArrayList<int[]> result = new ArrayList<>();
int[] currentPartition = new int[n];
int k=0; //اخرین ایندکس currentPartition
currentPartition[k] = n;
while (true) {
int[] temp = new int[k+1];
for(int i=0 ; i<=k ; i++) {
temp[i] = currentPartition[i];
}
result.add(temp);
int remained = 0;
while(k>=0 && currentPartition[k]==1) {
remained += currentPartition[k];
k--;
} }
if(k<0)
break;
currentPartition[k]--;
remained++;
while (remained > currentPartition[k]) {
currentPartition[k+1] = currentPartition[k];
remained -= currentPartition[k];
k++;
}
currentPartition[k+1] = remained;
k++;
}
int[][] output = new int[result.size()][];
for(int i=0 ; i<result.size() ; i++) {
output[i] = result.get(i);
}
return output;
}
public static void main() public static void main()
{ {