AttractiveCritter free response answer 2

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);
  }
 }
}

Get AP CS Help

2011 AP CS Exam Free Response Solutions

Recommended Practice Problems

2 thoughts on “AttractiveCritter free response answer

  1. Jess Feb 6,2012 11:04 pm

    I thought that the for loop iterator couldn’t do simultaneous things like adding and removing?? Wasn’t it just like an overseer??

    • Brandon Horn Feb 7,2012 6:31 am

      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.

Comments are closed.