Отзеркалить матрицу с нечетным количеством столбцов
Имеется задача: есть матрица, у которой элементы левой половины равны элементам правой половины относительно вертикали. При этом внутри класса хранится только одна половина матрицы. Мне удалось сделать корректный вывод, если количество столбцов четное, однако не имею понятия, как сделать с нечетным количеством столбцов. Буду рада, если кто поможет, объяснит
public MirrorMatrixVert(int n, int m){
super(n,m/2);
}
MirrorMatrixVert mmv1 = new MirrorMatrixVert(2,4);
mmv1.doRandomNumbers();
System.out.println("First Mirror Matrix is created");
System.out.println(mmv1);
MirrorMatrixVert mmv2 = new MirrorMatrixVert(4,2);
mmv2.doRandomNumbers();
System.out.println("Second Mirror Matrix is created");
System.out.println(mmv2);
Вывод:
First Mirror Matrix is created
4 1 4 1
4 2 4 2
Second Mirror Matrix is created
2 2
0 0
3 3
4 4 //вывелось правильно
MirrorMatrixVert mmv2 = new MirrorMatrixVert(4,3);
mmv2.doRandomNumbers();
System.out.println("Second Mirror Matrix is created");
System.out.println(mmv2);
Вывод:
Second Mirror Matrix is created
4 4
1 1
3 3
1 1 //неверно
Ответы (1 шт):
Автор решения: Дмитрий
→ Ссылка
Попробуйте так:
import java.util.Arrays;
public class MirrorMatrixVert {
private final Integer [][] sourceArray;
public MirrorMatrixVert(final Integer[][] sourceArray) {
this.sourceArray = sourceArray;
}
public MirrorMatrixVert apply() {
for (Integer[] array : sourceArray) {
for (int i = 0; i < array.length; i++) {
if (i >= array.length - 1 - i) break;
array[array.length - 1 - i] = array[i];
}
}
return this;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (Integer[] array : sourceArray) sb.append(Arrays.toString(array)).append("\r\n");
return sb.toString();
}
public static void main(String[] args) {
Integer [][] arr = {
{2,5,null,null},
{3,7,8,null,null}
};
MirrorMatrixVert mirrorMatrixVert = new MirrorMatrixVert(arr);
System.out.println(mirrorMatrixVert.apply());
}
}