Getting a "for each" loop in Java to run in different order everytime
- by R Stokes
Hi,
Basically my problem is that I'm trying to write a method that finds a random path in a graph of strings, which takes as it's parameters a start string, an integer length and a Vector of strings that will store the path. I'm attempting to do this by first adding the starting string to our blank vector, recursing through its neighbors until the vector's length (not including the start node) is the same as the integer length specified in the parameters. I've provided my code so far here:
public Vector<String> findRandomPathFrom(String n, int len, Vector<String> randomPath){
randomPath.add(n);
if (randomPath.size() == len + 1)
return randomPath;
for (String m : this.neighbours(n)){
if (!randomPath.contains(m) && findRandomPathFrom(m, len, randomPath) != null)
return randomPath;
}
path.setSize(path.size() - 1);
return null;
}
It seems to be working fine, returning a path with exactly the number of strings specified after the given start string. However, for any given starting string it generates the EXACT same path everytime, which kind of defeats the purpose of it being a random path generator. I'm guessing this problem is related to my "for each" loop, which loops through all the neighbouring strings of your current string. It seems to just be going with the first string in the neighbours vector every single time. Can anyone help me fix this problem so that it will choose a random neighbour instead of going in order?
tl;dr - Any way of getting a "for each" loop in java to process a collection in a random order as oppoosed to start-to-finsih?
Thanks in advance