Generation of the same sequence of random numbers

后端 未结 5 1916
广开言路
广开言路 2021-01-07 20:42

I want to generate random numbers in java, I know I should use existing methods like Math.random(), however, my question is: how can I generate the same sequence of numbers,

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-07 21:17

    An example of using the same seed repeatedly.

    public static void main(String... args) throws IOException {
        printDoublesForSeed(1);
        printDoublesForSeed(128);
        printDoublesForSeed(1);
        printDoublesForSeed(128);
    }
    
    private static void printDoublesForSeed(long seed) {
        double[] doubles = new double[10];
        Random rand = new Random(seed);
        for (int j = 0; j < doubles.length; j++) {
            doubles[j] = (long) (rand.nextDouble() * 100) / 100.0;
        }
        System.out.println("doubles with seed " + seed + " " + Arrays.toString(doubles));
    }
    

    prints

    doubles with seed 1 [0.73, 0.41, 0.2, 0.33, 0.96, 0.0, 0.96, 0.93, 0.94, 0.93]
    doubles with seed 128 [0.74, 0.53, 0.63, 0.41, 0.21, 0.2, 0.33, 0.74, 0.17, 0.47]
    doubles with seed 1 [0.73, 0.41, 0.2, 0.33, 0.96, 0.0, 0.96, 0.93, 0.94, 0.93]
    doubles with seed 128 [0.74, 0.53, 0.63, 0.41, 0.21, 0.2, 0.33, 0.74, 0.17, 0.47]
    

    EDIT An interesting abuse of random seeds.

    public static void main(String ... args) {
        System.out.println(randomString(-6225973)+' '+randomString(1598025));
    }
    
    public static String randomString(int seed) {
        Random rand = new Random(seed);
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<5;i++)
            sb.append((char) ('a' + rand.nextInt(26)));
        return sb.toString();
    }
    

    prints

    hello world
    

提交回复
热议问题