Hi all, I've racked my brains and torn the SDK documentation apart, but I can't find a way of randomly shuffling an array (in my case, it's an array of String objects - so that they display in a different order each time they're used). I found a way of shuffling a List item, but I'm damned if I can find a way to get an array into a List and turn the shuffled List back into an array of Strings. I'd especially like to seed it, so that the random sort is different each time. Any ideas how I could do this? Mick Flynn
Mick, I don't know of a precreated method in Java that will do such a shuffle for you. Certainly you could write your own shuffle method using Math.random() or the Random class (which has a setSeed() method). One way to do this would be to cycle through a loop n times (n = size of array), generating a random number from 1-n (or 0 - (n-1)) and copying the value in that position from the original array into a new "shuffled" array. You'd have to place your random numbers into a Hashmap or similar, and enclose the random number generator in a while loop checking for already-used values in the Hashmap using the containsKey() method.
Why actually shuffle the array? Why not just choose a random index every time you access it? Though I guess you may have a problem with choosing the same index multiple times, randomizing an array is pretty inefficient, as the code below shows... though hopefully it will help you out if you really need it...
Write once, run anywhere, because there's nowhere to hide! - /. A.C.
Scott, Nathan, The idea of choosing a random index every time I access the array would work wouldn't it...? But only if I had a way of flagging which indices have already been used... you see, I can't access the same one twice. Would I create a boolean array, all set to false, and set each one to true as it is accessed? That would work, wouldn't it? In any case, thanks a million to both of you! MF