【问题标题】:How to generate a random number from 1 to 100 only once?如何只生成一次从 1 到 100 的随机数?
【发布时间】:2013-09-10 10:09:05
【问题描述】:

我需要在 AS3 中生成一个 1 到 100 的随机数,不会生成两次。所以我需要生成每个数字,直到所有数字都完成。我该怎么做?

【问题讨论】:

    标签: actionscript-3 random numbers


    【解决方案1】:

    用数字 1 到 100 填充一个数组。

    随机洗牌(使用 Fisher-Yates 洗牌)。

    从第一个数组索引开始取每个数字...

    【讨论】:

    • 也许我遗漏了一些明显的东西,但你为什么要从索引 1 而不是 0 开始呢?
    【解决方案2】:

    用数字 1-100 填充数组“_randomNumbers”。每次您需要一个号码时,请使用以下内容:

    if (_randomNumbers.length>0) {
    newRandomNumber = _randomNumbers.splice( Math.floor(Math.random(_randomNumbers.length)), 1 )[0];
    }
    

    【讨论】:

      【解决方案3】:

      查看this for more detail

       class NonRepeatedPRNG {
      private final Random rnd = new Random();
      private final Set<Integer> set = new HashSet<>();
      public int nextInt() {
      for (;;) {
        final int r = rnd.nextInt();
        if (set.add(r)) return r;
      }
      }
      }
      

      【讨论】:

        猜你喜欢
        • 2011-01-23
        • 2016-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-02
        • 2014-10-28
        相关资源
        最近更新 更多