Using packages
[Agent practical 5 of 9]


So, how do we go about randomising the order we call our agents?


We could build our own, bespoke, randomiser, that randomises the order the agents are picked out of the array. However, with some small changes we can use methods built into classes distributed with Java. Java is distributed with a set of classes called the "Collections Framework". These are classes that store java.lang.Objects: i.e. can store pretty much any Java object. Using the angle-bracket notation we saw in the lectures, they can also be tighten up to work with specific classes.

One very popular member of this framework is the ArrayList. This is a reasonably efficient replacement for arrays which, for example, allows you to add and remove elements from an array without having to worry too much about enlarging or shortening the underlying array. Doing this yourself can be a real pain.

For us, however, the most significant advantage is that there is a static method Collections.shuffle() that takes in Collections members and shuffles them randomly. If we move our agents into an ArrayList, we can use this.

Given this, in your Model.java, import java.util.*; and make the following replacements:

-------------------------------------------------------------------

private Agent[] agents = new Agent[numberOfAgents];
private ArrayList <Agent> agents = new ArrayList <Agent>();

-------------------------------------------------------------------

for (int i = 0; i < agents.length; i++) {
   agents[i] = new Nibbler(world);
}


for (int i = 0; i < numberOfAgents; i++) {
   agents.add(new Nibbler(world));
}

-------------------------------------------------------------------

for (int i = 0; i < numberOfIterations; i++) {

   for (int j = 0; j < numberOfAgents; j++) {
      agents[j].run();
      System.out.println(i + " " + agents[j].getX() + " " + agents[j].getY() +
         " " + world.getDataValue(agents[j].getX(), agents[j].getY()));
   }

   if (stoppingCriteriaMet() == true) break;
}


for (int i = 0; i < numberOfIterations; i++) {

   Collections.shuffle(agents);
   for (int j = 0; j < agents.size(); j++) {
      agents.get(j).run();
      System.out.println(i + " " + agents.get(j).getX() + " " + agents.get(j).getY() +
         " " + world.getDataValue(agents.get(j).getX(), agents.get(j).getY()));
   }

   if (stoppingCriteriaMet() == true) break;
}


-------------------------------------------------------------------

Note the different notation for accessing values in an ArrayList. You can find the full documentation for an ArrayList in the ArrayList API docs.


When you're sure this is working, go on to looking at communication between agents.