I've been reading Game Coding Complete (4th Edition) and I'm having a few problems understanding the "Pseudo-Random Traversal of a Set" path in the "Grab Bag of Useful Stuff" section in Chapter 3.
Have you ever wondered how the “random” button on your CD player works? It will play every song on your CD randomly without playing the same song twice. That's a really useful solution for making sure players in your games see the widest variety of features like objects, effects, or characters before they have the chance of seeing the same ones over again.
After this description, it goes on to talk about an implementation in C++ that I've tried to implement in Java, but have been unable to replicate successfully. It also briefly describes how it works, but I don't get it either.
I found this StackOverflow answer to a similar question, but unfortunately the link to examples in the answer is dead and I don't understand the Wikipedia article either, although the description about what it does seems to describe what I'm looking for.
To be clear, I'm not looking for a way to randomly re-order a collection. I am looking for a way to randomly select an element from a collection exactly once before repeating.
Can someone explain how this behavior works and provide an example in Java? Thanks!
[EDIT] I figured it might be useful to have an excerpt of the implementation in here to help explain what I'm talking about.
Here's how it works. A skip value is calculated by choosing three random values greater than zero. These values become the coefficients of the quadratic, and the domain value (x) is set to the ordinal value of the set:
Skip = RandomA * (members * members) + (RandomB * members) + RandomC
Armed with this skip value, you can use this piece of code to traverse the entire set exactly once, in a pseudo-random order:
nextMember += skip;
nextMember %= prime;
The value of skip is so much larger than the number of members of your set that the chosen value seems to skip around at random. Of course, this code is inside a while loop to catch the case where the value chosen is larger than your set but still smaller than the prime number.