I realize this is an old thread, but I do not understand how this works. Specifically, I don't understand how an element avoids being selected more than once when the same index value reoccurs. This seems like magic to me. Clearly, I am missing something important here. How does
int pos = order[index]know to select the
order[--orderLen]value rather than the value from the random calculation?
baavgai, on 13 March 2009 - 07:23 AM, said:
Awww, that's cheating! 
Here's how you'd do it just another array, if you're interested:
Here's how you'd do it just another array, if you're interested:
import java.util.*;
public class Shuffle3 {
public static void main(String[] arguments) {
String names[] = { "Peter", "Patricia", "Hunter", "Sarah",
"Gabe", "Gina", "Rob", "John", "Zoey", "Tammy", "Robert",
"Sean", "Paschal", "Kathy", "Neleh", "Vecepia" };
int [] order = new int[names.length];
System.out.println("The original order:");
for (int i = 0; i < names.length; i++){
order[i] = i;
System.out.println(i + ": " + names[i]);
}
System.out.println("The new order:");
int orderLen = names.length;
for (int i = 0; i < names.length; i++){
int index = (int) (Math.random() * orderLen);
int pos = order[index];
System.out.println(pos + ": " + names[pos]);
order[index] = order[--orderLen];
}
}
}

New Topic/Question
Reply



MultiQuote







|