Note: GridWorld is no longer featured on the AP CS A Exam (since the 2015 Exam).

The Grid interface is an important part of the GridWorld Case Study. This practice test is intended to check your understanding of how to use the Grid interface to accomplish common tasks. You should have a copy of the Quick Reference available as you take this practice test.

Question 1

Consider the following code.

Grid<Actor> myGrid = new BoundedGrid<Actor>(4,5);
Location loc = /* construct */;
myGrid.isValid(loc);

Which of the following replacements for /* construct */ violate(s) the precondition of isValid?

I    new Location(4,5);
II   new Location(5,6);
III  null

(A) II only
(B) III only
(C) I and II only
(D) I, II, and III
(E) None of these violate the precondition.

Question 2

/**
 * Returns a list of the Actor objects in g.
 * Precondition: g != null
 */
public static ArrayList<Actor> getActors(Grid<Actor> g)
{
    /* implementation */
}

Give code to replace /* implementation */ to make getActors work as intended.

Question 3

Grid>Actor> g = new BoundedGrid<Actor>(4,5);
Location loc = /* construct */;
ArrayList<Location> locs = g.getValidAdjacentLocations(loc);
Collections.sort(locs);
System.out.println(locs);

Collections.sort sorts its explicit parameter in increasing order according to the ordering imposed by the compareTo method of the parameter’s elements. For example, the list of Integer objects [6, 1, 4, 2] would become [1, 2, 4, 6]. When an ArrayList is printed, the result of running the toString method on each element is printed.

Give the output produced by the above code segment for each of the following values for /* construct */ or state that the value violates the precondition of getValidAdjacentLocations. (Hint: Adjacent locations include diagonals.)

(A) new Location(0,2)
(B) new Location(3,0)
(C) new Location(4,5)
(D) null

See the Grid interface practice test solutions and explanations or review them with AP CS Tutor Brandon Horn.

Additional GridWorld resources