The AttractiveCritter problem from the 2011 AP Computer Science Exam is typical of free response problems that test GridWorld: The AP Computer Science Case Study. The problem requires you to extend the Critter class, determine which methods to override, and implement the entire subclass.
Review the AttractiveCritter free response problem with AP CS Tutor Brandon Horn.
AttractiveCritter
public class AttractiveCritter extends Critter { public ArrayList<Actor> getActors() { ArrayList<Actor> actors = new ArrayList<Actor>(); for (Location loc : getGrid().getOccupiedLocations()) actors.add(getGrid().get(loc)); actors.remove(this); return actors; } public void processActors(ArrayList<Actor> actors) { for (Actor a : actors) { int direction = a.getLocation().getDirectionToward(getLocation()); Location loc = a.getLocation().getAdjacentLocation(direction); if (getGrid().isValid(loc) && // validity check not strictly necessary getGrid().get(loc) == null) // empty check necessary a.moveTo(loc); } } }
2011 AP CS Exam Free Response Solutions |
Recommended Practice Problems |
I thought that the for loop iterator couldn’t do simultaneous things like adding and removing?? Wasn’t it just like an overseer??
In a foreach loop, it is not possible to change the structure (add to or remove from) of the list over which you are iterating. The foreach loop in the solution to getActors() adds to a different list, which is fine.