1

If I set seed in Random why always get same random number in below code:

private static void createArray(int[] x) {

    for(int i =0; i<x.length; i++){
        Random random = new Random(500l);

        x[i] = random.nextInt(100000); //53695
    }

}

I am getting 53695 for every run and entire loop.

Chowdappa
  • 1,580
  • 1
  • 15
  • 31
  • That's... how a seed works. If you set the seed to the same number every time, you'll get the same **pseudo**-random number every *n*th call (here: every 1st call, as you *always* seed before) to `nextInt()`. Seed only once at the beginning of your program. Or don't seed at all. – domsson Apr 13 '17 at 10:10

1 Answers1

2

Because that's what happens when you use the same seed in a pseudo-randomnumber generator. It's not random, it just looks "random enough", but it's all thanks to a deterministic mathematical formula.

Use SecureRandom if you need better randomness.

Here are some examples of seeds that provide "interesting" "random" numbers: http://insights.dice.com/2014/01/24/generating-random-numbers-javas-random-class/

Kayaman
  • 72,141
  • 5
  • 83
  • 121