获得“每个” Java中的循环每次都以不同的顺序运行
基本上我的问题是我正在尝试编写一种在字符串图中查找随机路径的方法,该方法将起始字符串、整数长度和将存储路径的字符串向量作为参数。我尝试通过首先将起始字符串添加到我们的空白向量中,递归遍历其邻居,直到向量的长度(不包括起始节点)与参数中指定的整数长度相同。到目前为止,我已经在这里提供了我的代码:
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;
}
它似乎工作正常,返回一个路径,该路径的字符串数量与给定的起始字符串之后指定的字符串数量完全相同。然而,对于任何给定的起始字符串,它每次都会生成完全相同的路径,这违背了它作为随机路径生成器的目的。我猜这个问题与我的“foreach”循环有关,该循环遍历当前字符串的所有相邻字符串。它似乎每次都只使用邻居向量中的第一个字符串。任何人都可以帮我解决这个问题,以便它会选择一个随机邻居而不是按顺序进行?
tl;博士->有什么方法可以让java中的“for every”循环以随机顺序处理集合,而不是从开始到结束?
提前致谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
Collections.shuffle()
在遍历邻居列表之前。Use
Collections.shuffle()
on the list of neighbours before iterating over it.