代码之家  ›  专栏  ›  技术社区  ›  chinloyal

生成第一个为零的随机数

  •  2
  • chinloyal  · 技术社区  · 6 年前

    我知道如何得到一个介于0和任何数字之间的随机数范围。

    但我想知道的是,因为随机数生成器不是真正的随机数,它遵循一个特定的算法,例如,如果您传递一个20的种子。然后它将始终生成相同的数字序列:17、292、0、9。

    所以我明白了。由于它遵循特定的算法,有没有一种方法可以强制生成器始终从零或任何其他数字开始?

    但在我的情况下,特别是零。

    2 回复  |  直到 6 年前
        1
  •  0
  •   matt    6 年前
    public static void main (String[] args) throws java.lang.Exception
        {
            int x = -1;
            long seed = 0;
            int xxx = 100;
            while(x!=0){
    
                Random s = new Random(seed++);
                x = s.nextInt(xxx);
    
            }
            System.out.println("seed " + (seed-1) + " gives " + new Random(seed-1).nextInt(xxx));
    
        }
    

    这将找到一个种子,对于给定的模数,下一个int将为零。(本例中恰好是18)。

        2
  •  5
  •   Benoit    6 年前

    无需破解随机类,只需编写自己的:

    public class RandomGenerator {
    
        private int bound;
        private Random random;
        private boolean firstCall = true;
    
        public RandomGenerator(int bound, long seed) {
            this.bound = bound;
            random = new Random(seed)
        }
    
        public int next() {
            if (firstCall) {
                firstCall = false;
                return 0;
            }
            return random.nextInt(bound);
        }
    }