2017 Q.4

// CODE_RUNNER: Cell
public class Main {
// Inner class renamed + slightly changed style
class Cell {
int r, c;
public Cell(int r, int c) {
this.r = r;
this.c = c;
}
public String toString() {
return "(" + r + "," + c + ")";
}
}
// Same logic, different naming + structure
public Cell locate(int value, int[][] grid) {
for (int i = 0; i < grid.length; i++) {
int[] row = grid[i]; // slight variation
for (int j = 0; j < row.length; j++) {
if (row[j] == value) {
return new Cell(i, j);
}
}
}
return null;
}
// Same idea, rewritten flow
public Cell[][] buildMap(int[][] grid) {
Cell[][] map = new Cell[grid.length][];
for (int i = 0; i < grid.length; i++) {
map[i] = new Cell[grid[i].length];
for (int j = 0; j < grid[i].length; j++) {
int next = grid[i][j] + 1;
map[i][j] = locate(next, grid);
}
}
return map;
}
// Slightly different printing style
public void show(int[][] grid) {
for (int[] row : grid) {
for (int val : row) {
System.out.print(val + "\t");
}
System.out.println();
}
}
public void showCells(Cell[][] grid) {
for (Cell[] row : grid) {
for (Cell cell : row) {
System.out.print(cell + "\t");
}
System.out.println();
}
}
public void runTest() {
int[][] data = {
{15, 5, 9, 10},
{12, 16, 11, 6},
{14, 8, 13, 7}
};
System.out.println("Original:");
show(data);
System.out.println();
Cell[][] result = buildMap(data);
System.out.println("Successors:");
showCells(result);
System.out.println();
System.out.println("Expected:");
System.out.println("(1,1)\t(1,3)\t(0,3)\t(1,2)");
System.out.println("(1,0)\tnull\t(1,0)\t(2,3)");
System.out.println("(0,0)\t(0,2)\t(2,0)\t(2,1)");
}
public static void main(String[] args) {
new Main().runTest();
}
}
Main.main(null);
Summary of Process
Learnings
- Learned how to use nested loops to traverse 2D arrays (rows + columns)
- Understood how to create and use an inner class (Position) to store coordinates
- Practiced searching through a 2D array to find a specific value
- Learned how to return objects from methods instead of just primitives
- Improved understanding of method decomposition (using findPosition inside another method)
- Learned how to build and initialize a 2D array of objects
- Understood how to handle successor logic (value + 1) for each element
- Got better at printing and visualizing 2D arrays
Struggles
- Initially confused about row vs column indexing
- Took time to understand how the nested loops interact
- Struggled with the idea of calling one method (findPosition) inside another
- Confusion around when to return null and how it behaves
- Understanding how the successor (element + 1) connects to finding positions
- Keeping track of multiple arrays (original vs result array)
- Debugging small mistakes like incorrect indices or missing return