3

如果有类似的 for 循环

for ( int i = 0; i <= 10; i++ )
{
   //block of code
}

我想要实现的是,在第一次迭代之后,我的值不必为 1,它可以是 1 到 10 之间的任何值,我不应该再次为 0,对于其他迭代也是如此。

4

3 回答 3

7

简单算法:

  • 创建一个包含从 0 到 10 的数字的数组
  • 洗牌
  • 遍历该数组并检索初始集合中的相应索引

在 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);
    }
}
于 2013-01-11T11:13:42.947 回答
6

是的,您可以这样做:首先,创建数字的随机排列0.. N-1,然后像这样迭代:

int[] randomPerm = ... // One simple way is to use Fisher-Yates shuffle
for (int i in randomPerm) {
    ...
}

链接到 Fisher-Yates 洗牌。

于 2013-01-11T11:14:10.760 回答
2

“洗牌”方法可能是最简单的,但以随机顺序将它们拉出来也可以;这样做的主要问题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);
}
于 2013-01-11T11:17:37.220 回答