I have been asked to write Java method code to do the below:
+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+
| 0 | | | | 0 |
+---+---+---+---+---+
| 0 | | | | 0 |
+---+---+---+---+---+
| 0 | | | | 0 |
+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+
I am assuming that they are NOT asking me to create a char[5][5]; i.e :
char[][] grid = {
{'0','0','0','0','0'},
{'0',' ',' ',' ','0'},
{'0',' ',' ',' ','0'},
{'0',' ',' ',' ','0'},
{'0','0','0','0','0'}
};
I am assuming that the method will take a 2D array of int i.e int[][] and just reset the fence values to zero, and not changing the inner values. And that the array sizes is not fixed.
Having assumed that, I came up with below answer:
// Original answer
public int[][] initGrid1(int[][] grid) {
int initVal = 0;
int maxRows = grid.length;
int maxCols = grid[0].length;
for (int rows = 0; rows < grid.length; rows++) {
for (int cols = 0; cols < grid[0].length; cols++) {
if (rows == 0 || rows == maxRows - 1) {
grid[rows][cols] = initVal;
}
if (cols == 0 || cols == maxCols - 1) {
grid[rows][cols] = initVal;
}
}
}
return grid;
}
The response I got was: Isn't there a simpler way to do this?
Below are some of options I later came up with. I would like to know if you know of simpler way to do. Hoping to do this with Java8 features but found it difficult as individual occurrence needed to be identified for location.
// Option 2
public int[][] initGrid2(int[][] grid) {
int initVal = 0;
int maxRow = grid.length - 1;
int maxCol = grid[0].length - 1;
for (int rows = 0; rows < grid.length; rows++) {
grid[rows][0] = initVal;
grid[rows][maxCol] = initVal;
for (int cols = 0; cols < grid[0].length; cols++) {
grid[0][cols] = initVal;
grid[maxRow][cols] = initVal;
}
}
return grid;
}
If the grid is assumed to be a square.
// Option 3
public int[][] initGrid3(int[][] grid) {
int initVal = 0;
int maxlen = grid.length - 1;
for (int j = 0; j < grid.length; j++) {
grid[j][0] = initVal;
grid[j][maxlen] = initVal;
grid[0][j] = initVal;
grid[maxlen][j] = initVal;
}
return grid;
}
If I traverse through the array with a cursor (c):
// Option 4
public int[][] initGrid4(int[][] grid) {
int initVal = 0;
int xL = grid.length;
int yL = grid[0].length;
int max = xL * yL;
for (int c = 0; c < max; i++) {
int x = c / xL;
int y = (c == 0) ? 0 : c % yL;
if (x == 0 || x == (xL - 1)) {
grid[x][y] = initVal;
}
if (y == 0 || y == (yL - 1)) {
grid[x][y] = initVal;
}
}
return grid;
}
Using Java 8 feature, I was stuck with below, I don't if there is an option here:
grid[0] = IntStream.range(0, grid.length).map(i -> 0).toArray();
...don't know what to do in between.
grid[maxlen-1] = IntStream.range(0, grid.length).map(i -> 0).toArray();
1) So the big question; what is simpler?: (readability and maintainability) or smaller code or using latest features? Of course your assistance should not be just words but also code snippet.
2) And do you agree with my first answer?