Hi people, I just wanted to know what is the best way to un-order the elements in an ordered array in Java, Thanks
+5
A:
I think you want Collections.shuffle(List)
? If not that, you will need to give us more details about what you're trying to do.
birryree
2010-10-14 00:58:52
And you can be fairly sure that the shuffle algorithm of the Collections.shuffle() is pretty good. The standard JavaSE api is incredibly well tested. (Whoa... didn't want to sound like a sell speech)
Eric-Karl
2010-10-14 01:07:36
That was exactly what I was looking for, thank you people!
Joaquín L. Robles
2010-10-15 11:39:55
+1
A:
I don't know much Java, so there may be better way, but this'll do the trick nicely.
Fisher-Yates shuffle from Wikipedia:
static Random rng = new Random();
public static void shuffle(int[] array) {
// i is the number of items remaining to be shuffled.
for (int i = array.length; i > 1; i--) {
// Pick a random element to swap with the i-th element.
int j = rng.nextInt(i); // 0 <= j <= i-1 (0-based array)
// Swap array elements.
int tmp = array[j];
array[j] = array[i-1];
array[i-1] = tmp;
}
}
spender
2010-10-14 00:59:59
+2
A:
You want to shuffle that array using a good algorithm.
I would trust Collections#shuffle to implement this properly. If you need it to work on the array directly, implement the algorithm in your own helper method.
Thilo
2010-10-14 01:00:06
While this seems technically correct, it was (probably) downvoted because it's a very, very short answer. Compare your answer to @kuropenguin -- his was upvoted while yours was downvoted. (Just trying to help :-)
Josh
2010-10-14 01:04:15
For a very short answer, it is not even very good. Maybe "Collections.shuffle" (just one more character) would not have been downvoted.
Thilo
2010-10-14 01:11:58