Successors

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.

Part A

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 reference 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

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[][] getSuccessorArray( 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.

Why ClassCube?

Are you spending too much time grading your students' source code?

ClassCube is an online tool for Computer Science teachers that allows you to create lab assignments for your students. They'll submit their code online and ClassCube will automatically grade it for you.

More Info …

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>