Looking for review, good practices, optimizations, clean code tips etc.
/**
* Flip the columns.
*
* Complexity:
* O(row * col)
*
*/
public final class Mirror {
private Mirror () { }
/**
* Given a matrix create a mirror image,
*
* @param m the input matrix
* @throws NPE if exception occurs.
*/
public static void mirrorPatch(int[][] m) {
// for each row.
for (int i = 0; i < m.length; i++) {
// for each column
flipRow(m[i]);
}
}
private static void flipRow(int[] row) {
int length = row.length;
// simple swap of each element.
for (int i = 0; i < length/2; i++) {
int x = row[i];
row[i] = row[length -1 - i];
row[length -1 - i] = x;
}
}
public static void main(String[] args) {
// even number of columns.
int[][] m = { {1, 2, 3, 4} , {10, 20, 30, 40}};
mirrorPatch(m);
/*
* Informally verifying that output is:
* 4 3 2 1
* 40 30 20 10
*
*/
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[0].length; j++) {
System.out.print(m[i][j] + " ");
}
System.out.println();
}
System.out.println("-----------------------------------");
// odd number of columns.
/*
* Informally verifying that output is:
* 5 4 3 2 1
* 50 40 30 20 10
*/
int[][] m1 = { {1, 2, 3, 4, 5} , {10, 20, 30, 40, 50}};
mirrorPatch(m1);
for (int i = 0; i < m1.length; i++) {
for (int j = 0; j < m1[0].length; j++) {
System.out.print(m1[i][j] + " ");
}
System.out.println();
}
System.out.println("-----------------------------------");
}
}