如果有像
这样的for循环for ( int i = 0; i <= 10; i++ )
{
//block of code
}
我想要实现的是,在第一次迭代之后,i值不必为1,它可以是1到10之间的任何值,我不应该再次为0,对于其他迭代也是如此。
答案 0 :(得分:7)
简单算法:
在Java中:
public static void main(String[] args) throws Exception {
List<Integer> random = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Collections.shuffle(random);
List<String> someList = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");
for (int i : random) {
System.out.print(someList.get(i));
}
}
输出:
ihfejkcadbg
修改强>
现在我重读了它,你也可以简单地改组初始集合并循环:
public static void main(String[] args) throws Exception {
List<String> someList = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j");
//make a copy if you want the initial collection intact
List<String> random = new ArrayList<> (someList);
Collections.shuffle(random);
for (String s : random) {
System.out.print(s);
}
}
答案 1 :(得分:6)
是的,你可以这样做:首先,创建一个random permutation数字0
.. N-1
,然后像这样迭代:
int[] randomPerm = ... // One simple way is to use Fisher-Yates shuffle
for (int i in randomPerm) {
...
}
答案 2 :(得分:2)
“shuffle”方法可能是最简单的方法,但以随机顺序将它们拉出也可以起作用;这个问题的主要问题是RemoveAt
相对昂贵。洗牌会更便宜。包括完整性:
var list = new List<int>(Enumerable.Range(0, 10));
var rand = new Random();
while (list.Count > 0) {
int idx = rand.Next(list.Count);
Console.WriteLine(list[idx]);
list.RemoveAt(idx);
}