【问题标题】:Can I iterate through a for loop randomly instead of sequentially?我可以随机而不是顺序地遍历 for 循环吗?
【发布时间】:2013-01-11 11:12:00
【问题描述】:

如果有类似的for循环

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

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

【问题讨论】:

    标签: c# java loops for-loop control-structure


    【解决方案1】:

    简单算法:

    • 创建一个包含从 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);
        }
    }
    

    【讨论】:

      【解决方案2】:

      是的,您可以这样做:首先,创建一个由数字 0..N-1 组成的 random permutation,然后像这样迭代:

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

      Link to Fisher-Yates shuffle.

      【讨论】:

        【解决方案3】:

        “洗牌”方法可能是最简单的,但是以随机顺序将它们拉出来也可以;主要问题是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);
        }
        

        【讨论】:

        • 这个回答了问题,如果它是 0 到 10 ,如果 Enumerable range start seed 来自一个非零数字,例如 Enumerabl.Range(5,10)
        • @101010 您将在大约 2 行代码中添加偏移量;不是个大人物
        猜你喜欢
        • 2021-04-09
        • 2013-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-26
        • 1970-01-01
        • 1970-01-01
        • 2017-06-30
        相关资源
        最近更新 更多