This content has been marked as final. Show 3 replies
that's not rothrock's original code.
but to use it, apply the shuffle() method once. you then have a new array whose elements are shuffled. you would loop throught them from index 0 to the last index to access the original array elements in random order without repeats.
Oh, sorry, I'd thought that I'd read it accredited to him, who did come up with it? was it you kg?
Yeah that's something is was thinking too, if you loop through the new array, then when you reach the end, shuffle again, that would keep repeats to a minimum, but it is still possible that on reshuffle you could repeat the last element in the new shuffle, right? much less frequently of course.
a test for this:
The algorithm used in that code is a very old algorithm for "shuffling." Many people have independantly implemented it to create the shuffle. I've just been one of its biggest proponents and find ways to use it for so many things. Additionally there are several other ways to shuffle, but testing has shown that this is pretty much the fastest.
Recently I've done some work building math games for Kindergarten through Fifth Grade and we had many occasions to use the shuffle() when generating problem sets. Yes there is nothing built into the shuffle() that prevents the last element of the previous array from being the first element of the newly shuffled array(). Generally that hasn't been a concern, but if you are worried about it, here is what I do.
I save the last element in a varialbe and then I put the shuffle in a do while loop - testing on whether the first element of the shuffled array is equal to the variable. Usually it runs once, but occasionally it might have to run the shuffle a couple times. (The speed of this shuffle approach is good here.)
And yes the general idea is that once shuffled, the randomness is now orderly. You just step through one at a time in a neat and easy to track way. Just because you might be the type who likes this, I'll share my favorite way that I used it with the math games. We needed six digit numbers that were divisible by 2, 3, 5, 6, and/or 10. There are an awful lot of six digit numbers and just putting them all in an array and suffling took too long. Additionally we only wanted the appearance of "random" it wouldn't do to have all the numbers be in the 100 thousands or something like that.
So I made an array of the numbers, say from 100,000 to 124,999 and from 125,000 to 149,9999 and so on. I then put those arrays into an array and shuffled it. So i've gone from shuffling 899,999 items to shuffling 36. I would then take one of those blocks of 25,000 and shuffle it and maybe pull the first 2 or 3 that were divisible and then discard that array. and move on to the next. So in then end to get 15 or so "random" numbers I would only need to shuffle 36+5*25,000= 125,036 elements.
Anyways, there are lots of ways to use it creatively.