Complete the GridTools practice problem before reviewing the solution.

Review the GridTools solution with AP CS Tutor Brandon Horn.

Part (a) blueNeighbors method

public List<Actor> blueNeighbors(Location loc)
{
    List<Actor> blueNeighbors = new ArrayList<Actor>();

    for (Actor neighbor : gr.getNeighbors(loc))
        if (neighbor.getColor().equals(Color.BLUE))
            blueNeighbors.add(neighbor);

    return blueNeighbors;
}

Part (b) actorsWithBlueNeighbors method

public List<Actor> actorsWithBlueNeighbors()
{
    List<Actor> haveBlueNeighbors = new ArrayList<Actor>();

    for (Location occupiedLoc : gr.getOccupiedLocations())
        if (blueNeighbors(occupiedLoc).size() > 0)
            haveBlueNeighbors.add(gr.get(occupiedLoc));

    return haveBlueNeighbors;
}

Part (c) actorWithMostBlueNeighbors method

public Actor actorWithMostBlueNeighbors()
{
    List<Actor> haveBlueNeighbors = actorsWithBlueNeighbors();

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

    Actor hasMostBlueNeighbors = haveBlueNeighbors.get(0);

    for (int i = 1; i < haveBlueNeighbors.size(); i++)
    {
        if (blueNeighbors(haveBlueNeighbors.get(i).getLocation()).size() >
                blueNeighbors(hasMostBlueNeighbors.getLocation()).size())
        {
            hasMostBlueNeighbors = haveBlueNeighbors.get(i);
        }
    }

    return hasMostBlueNeighbors;
}

Part (d) getEmptyWithinSpots method

public List<Location> getEmptyWithinSpots(Location center, int spots)
{
    List<Location> emptyWithinSpots = new ArrayList<Location>();

    for (int row = center.getRow() - spots; row <= center.getRow() + spots; row++)
    {
        for (int col = center.getCol() - spots; col <= center.getCol() + spots; col++)
        {
            Location loc = new Location(row, col);
            if (gr.isValid(loc) && gr.get(loc) == null)
                emptyWithinSpots.add(loc);
        }
    }

    emptyWithinSpots.remove(center);

    return emptyWithinSpots;
}