I have an Ant Colony Simulator. It is a 27 x 27 grid, and there is a Forager Ant class which locates food and the highest pheromone levels. I need to randomly generate the movement within a range.
This is a very large project, so here is only the method in question (if that's enough):
private GridNode locateHighestPherms() {
Random randomNode = new Random();
LinkedList<GridNode> neighborNodeList = gridLocation.getNeighboringNodes(); //a List of Node Objects that keeps track of adjacent nodes
LinkedList<GridNode> randomGridNode = new LinkedList<>(); //random destination Node
for(Iterator<GridNode> gridNodeIterator = neighborNodeList.iterator(); gridNodeIterator.hasNext();) {
GridNode alreadyVisited = gridNodeIterator.next();
if(foragerMoveHistory.contains(alreadyVisited) || !alreadyVisited.isVisible()) {
gridNodeIterator.remove();
}
}
if(neighborNodeList.size() == 0) {
neighborNodeList = gridLocation.getNeighboringNodes();
}
GridNode nodeWithMostPherms = neighborNodeList.get(0);
for(int checkNode = 1; checkNode < neighborNodeList.size(); checkNode++) {
if(nodeWithMostPherms.isVisible() && nodeWithMostPherms.getPheromoneUnit() < neighborNodeList.get(checkNode).getPheromoneUnit()) {
nodeWithMostPherms = neighborNodeList.get(checkNode);
}
}
for (GridNode neighborNode : neighborNodeList) {
if ((neighborNode.getPheromoneUnit() == nodeWithMostPherms.getPheromoneUnit()) && neighborNode.isVisible()) {
randomGridNode.add(neighborNode);
}
}
//DEBUGGING
//System.out.println(randomGridNode.size());
nodeWithMostPherms = randomGridNode.get(randomNode.nextInt(randomGridNode.size()));
//nodeWithMostPherms = randomGridNode.get(RandomInstance.randomNumberGen(1, randomGridNode.size()));
return nodeWithMostPherms;
}
}
Right there ^ the assignment to nodeWithMostPherms is where I need to access the next Random number. However, when I originally tried the code that's commented out, it was crashing because at times I was trying to access zero when the list size was zero.
I will show you my RandomInstance class. It's short and sweet:
import java.util.Random;
public class RandomInstance {
static int randomNumber;
public static int randomNumberGen(int lowRange, int highRange) {
Random numberGenerator = new Random(); //I would prefer not to have this.
randomNumber = numberGenerator.nextInt(highRange - lowRange + 1) + lowRange;
/** EXAMPLE FOR REFERENCE
* setFoodUnitAmount(RandomInstance.randomNumberGen(500, 1000));
*/
return randomNumber;
}
}
The reason I have my own Random class is because there are many instances of random numbers that are generated, and it was suggested to create our own so we don't have a bunch of instances of java.util.Random all over the place.
Does anyone have any suggestions on how I can make this fit my RandomInstance class?
Aucun commentaire:
Enregistrer un commentaire