我可以随机迭代for循环而不是顺序吗?

Cod*_*tic 3 c# java loops for-loop control-structure

如果有一个for循环就好

for ( int i = 0; i <= 10; i++ )
{
   //block of code
}
Run Code Online (Sandbox Code Playgroud)

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

ass*_*ias 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));
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)


das*_*ght 6

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

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

链接到Fisher-Yates shuffle.