package holidbaha;
/* 2. Дан целочисленный двумерный массив размера M×N, заполненный построчно случайными
* значениями в диапазоне от -99 до 99. Этот массив вывести на экран. Заменить исходный
* массив новым, в котором удален ее первый столбец, содержащий только положительные
* элементы (номер удаляемого столбца может быть любым от 0 до N-1!). Получившийся массив
* вывести на экран. Если требуемого столбца нет, то вывести массив без изменений.
* М и N задаются в main(). */
public class Solution2 {
public static void main(String[] args) {
int m = 3;
int n = 3;
int[][] matrix = new int[m][n];
fillMatrixRandom(-99, 99);
displayMatrix();
rebuildMatrix(findPositiveColumn());
displayMatrix();
}
public static void fillMatrixRandom(int from, int to) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = (int) (Math.random() * (to - from) + from);
}
}
}
public static void displayMatrix() {
for (int[] row : matrix) {
for (int cell : row) {
System.out.print((cell < 0 ? cell < -9 ? " " : " " : cell > 9 ? " " : " ") + cell);
}
System.out.println();
}
System.out.println("----".repeat(n));
}
public static int findPositiveColumn() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[j][i] < 0) break;
if (j == m - 1) return i;
}
}
return -1;
}
public static void rebuildMatrix(int column) {
if (column == -1) return;
int[][] newMatrix = new int[m][n - 1];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n - 1; j++) {
newMatrix[i][j] = matrix[i][j < column ? j : j + 1];
}
}
matrix = newMatrix;
}
}
Gunbilig
Level 1
Как представить?
New
Comments
- Popular
- New
- Old
You must be signed in to leave a comment
This page doesn't have any comments yet