The GridChecker problem from the 2010 AP Computer Science Exam is typical of free response problems that test GridWorld: The AP Computer Science Case Study. The problem requires you to run multiple methods of the Grid interface with correct implicit and explicit parameters and to handle the return values.

GridChecker is #4 from the 2010 AP Computer Science Free Response.

https://secure-media.collegeboard.org/apc/ap10_frq_computer_science_a.pdf

Part (a) actorWithMostNeighbors method

public Actor actorWithMostNeighbors()
{
    List<Location> occupiedLocations = gr.getOccupiedLocations();

    if(occupiedLocations.size() == 0)
        return null;

    Location locWithMostNeighbors = occupiedLocations.get(0);

    for(Location loc : occupiedLocations)
        if(gr.getOccupiedAdjacentLocations(loc).size() >
                gr.getOccupiedAdjacentLocations(locWithMostNeighbors).size())
            locWithMostNeighbors = loc;

    return gr.get(locWithMostNeighbors);
}

Part (b) getOccupiedWithinTwo method

public List<Location> getOccupiedWithinTwo(Location loc)
{
    List<Location> occupiedWithinTwo = new ArrayList<Location>();

    for (int row = loc.getRow() - 2; row <= loc.getRow() + 2; row++)
    {
        for (int col = loc.getCol() - 2; col <= loc.getCol() + 2; col++)
        {
            Location locToCheck = new Location(row, col);

            if (gr.isValid(locToCheck) && gr.get(locToCheck) != null)
                occupiedWithinTwo.add(locToCheck);
        }
    }

    occupiedWithinTwo.remove(loc);

    return occupiedWithinTwo;
}

2010 AP CS Exam Free Response Solutions

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on GridChecker