-Dman100-
asked on
randomize array of integers
I am trying to shuffle an array of 52 integers using the following method:
I want to randomize the array so that the integers are out of order and unique. Right now, the array is randomized, but it is not unique. I want all the integers to be unique. I also want to make sure the order of the array is never 0,1,2,3,4,5,6,7...etc...51 .
I'm using the Salesforce apex language above, which is a derivative of Java. I don't have access to the shuffle method and the random object. I need to accomplish it with the above code structure.
Any help is appreciated.
Thanks.
public static List<Integer> shuffleArray(Integer[] arr) {
Integer[] randomizedArray = new Integer[]{};
for(Integer i=0; i<arr.size(); i++) {
Double dbl = math.random() * arr.size();
randomizedArray.add(dbl.intValue());
}
return randomizedArray;
}
I want to randomize the array so that the integers are out of order and unique. Right now, the array is randomized, but it is not unique. I want all the integers to be unique. I also want to make sure the order of the array is never 0,1,2,3,4,5,6,7...etc...51
I'm using the Salesforce apex language above, which is a derivative of Java. I don't have access to the shuffle method and the random object. I need to accomplish it with the above code structure.
Any help is appreciated.
Thanks.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you!
Once you've done this for every element in the array, you can be sure that it is shuffled,
No you can't be sure. The loop index could map to any of the selected random number(s), and so no swap would take place.
ASKER
Open in new window
This is does work most of times, but I'm noticing my unit test fails occassionly because an index in the original list can equal an index in the randomized list.
Perhaps there is a better way to test that the new list is randomized? Suggestions?
In my test, I just want to show that the array has been randomized.
Thanks for the help! I appreciate it!
Regards.