| Author |
Shuffling Arrays (or other Collection)
|
Martin Clifford
Greenhorn
Joined: Dec 02, 2002
Posts: 23
|
|
Hi all! I know this mihgt be a stupid question, but I haven't been able to find it throughout all the API's. Is there a class/method that can shuffle an array of elements into a random order? Or has anyone come up with an algorithm/method to do so? Thanks in advance!
|
Martin
|
 |
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18671
|
|
For a collection coll: Collections.shuffle(coll); For an Object[] array arr: Collections.shuffle(Collections.asList(arr)); For an array of primitives, you'd have to replace it with an array or Object wrappers first - or write your own version of shuffle() which works for the desired primitive type.
|
"I'm not back." - Bill Harding, Twister
|
 |
Martin Clifford
Greenhorn
Joined: Dec 02, 2002
Posts: 23
|
|
Jim, thanks for the reply! However, as I'm still new to Collections, and Polymorphism as well, I don't know which collection closely resembles arrays (i.e., being able to loop through elements to check for values). Basically, I want to shuffle an array, then check to see if the array is in numerical order. Sort of a probability thing. I've come close, and have since posting even come up with my own algorithm for shuffling a primitive array, but my method does not preserve the unique integers (as Random things sometimes don't). Do you think you might be able to provide a sample of shuffling an array with the Collections.shuffle() method? Thanks!
|
 |
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18671
|
|
However, as I'm still new to Collections, and Polymorphism as well, I don't know which collection closely resembles arrays (i.e., being able to loop through elements to check for values). Well, you can loop through any Collection. Since the order is important, we want a List of some sort, and the shuffle() method works best for a collection which implements RandomAccess as well. ArrayList would be a good choice among the standard collections - however Arrays.asList() is even easier to use in this case. See the documentation for each of these methods/classes for more info. Do you think you might be able to provide a sample of shuffling an array with the Collections.shuffle() method? Thanks! Well, I already did - but to make it more explicit:
|
 |
 |
|
|
subject: Shuffling Arrays (or other Collection)
|
|
|