One Two Three
One Two Three

Reputation: 23497

When will the sequence of numbers produced by Random.nextInt() repeat

Does anyone know if the Java's Random.nextInt() will ever repeat itself after sometime?

Concretely, is there such a number n such that the following two lists are equal?

List<Integer> a = new LinkedList<>();
List<Integer> b = new LinkedList<>();

for (int i = 0; i < n; ++i)
   a.add(randObject.nextInt());

for (int i = n; i <= n * 2 ; ++i)
   b.add(randObject.nextInt());

Is it guaranteed that every random object has a period? (Note: Objects of different seeds don't have to have the same period)

Upvotes: 2

Views: 1207

Answers (2)

NPE
NPE

Reputation: 500157

Does anyone know if the Java's Random.nextInt() will ever repeat itself after sometime?

Yes it will. Since the generator has a finite amount of state, the generated sequence has a finite period.

Concretely, what is the number n such that the following two lists are equal?

That's not specified and depends on the Java implementation.

Is it guaranteed that there will always be such n for each Random object, regardless of what its seed is?

The period is finite. However, it's not necessarily the case that it's the same for every seed.

Upvotes: 4

ogzd
ogzd

Reputation: 5692

If you are really really really lucky enough, yes. Otherwise no.

But from the javadoc

The general contract of nextInt is that one int value is pseudorandomly generated and returned. All 2^32 possible int values are produced with (approximately) equal probability.

Upvotes: -1

Related Questions