The fourth question on the 2017 AP Computer Science Exam tasked you with processing a 2d `int`

matrix and using the values to fill in a 2d matrix with references of an arbitrary class, `Position`

.

In the first part you were to implement a method called `findPosition`

that went through a 2d array of `int`

values and return a new `Position`

object based on where a value is found.

```
public static Position findPosition(int num, int[][] intArr) {
for (int r=0; r<intArr.length; r++) {
for (int c=0; c<intArr[r].length; c++) {
if (intArr[r][c] == num) {
return new Position(r, c);
}
}
}
return null;
}
```

In general, if you’re given an array to process on the AP exam you’re going to want to iterate through each value. In this case we need a nested loop to go through rows and columns.

We’ll then compare the value at each cell with the value `num`

we’re looking for. When it’s found we want to create and return a new `Position`

object based on the row and column where `num`

was found.

If we get all the way through `intArr`

then we’ll return `null`

.

Part B expects you to call the `findPosition`

method that you created in Part A to build a 2d matrix of `Position`

objects.

```
public static Position[][] getSuccessoryArray(int[][] intArr) {
Position[][] out = new Position[intArr.length][intArr[0].length];
for (int r=0; r<intArr.length; r++) {
for (int c=0; c<intArr[r].length; c++) {
out[r][c] = findPosition(intArr[r][c] + 1, intArr);
}
}
return out;
```

For this we’re going to create a new `Position`

matrix that’s the same size as the source matrix `intArr`

. We’ll return `out`

at the end.

And like Part A we’ve got a 2d array to process so we’ll go through each cell using nested loops.

The problem description tells you that at each element in the matrix you should fill in a `Position`

object matching the row and column where you could find the value that’s one more than the cell you’re at. The PDF from College Board for this problem has a diagram that would help way more than I can do with text.

This site contains affiliate links. If you click an affiliate link and make a purchase we may get a small
commission. It doesn't affect the price you pay, but it is something we must disclose.