2
\$\begingroup\$

I'm trying to randomly shuffle an collection of integers within a List and I have came up with two shuffling method that does the job. However, I'm not sure which one works better. Does any one have any comments or suggestions?

public class TheCollectionInterface {
 public static <E> void swap(List<E> list1, int i, int j){
 E temp = list1.get(i);
 list1.set(i, list1.get(j));
 list1.set(j, temp);
 }
//alternative version 
// public static void shuffling(List<?> list, Random rnd){
// for(int i = list.size(); i >= 1; i--){
// swap(list, i - 1, rnd.nextInt(i));
// }
// }
 public static <E> void shuffling(List<E> list1, Random rnd){
 for(int i = list1.size(); i >= 1; i--){
 swap(list1, i - 1, rnd.nextInt(list1.size()));
 }
 }
 public static void main(String[] args) {
 List<Integer> li2 = Arrays.asList(1,2,3,4,5,6,7,8,9);
 Random r1 = new Random();
 TheCollectionInterface.shuffling(li2, r1);
 System.out.println(li2);
 }
}
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Mar 12, 2016 at 2:21
\$\endgroup\$
2
  • \$\begingroup\$ Did you consider Collections.shuffle()? \$\endgroup\$ Commented Mar 12, 2016 at 2:26
  • \$\begingroup\$ yes, that's another alternative, but I just want to come up with a shuffling method myself, practice with the logic :) \$\endgroup\$ Commented Mar 12, 2016 at 2:28

1 Answer 1

4
\$\begingroup\$

Your algorithm doesn't have simple uniform distribution over !n. Your alternative do has it, is actually a known algorithm named Fisher–Yates shuffle.

answered Mar 12, 2016 at 2:31
\$\endgroup\$
1
  • \$\begingroup\$ Thank you very much for the comment! Could you please explain in a bit more detail why my algorithm doesn't have simple uniform distribution over !n? \$\endgroup\$ Commented Mar 12, 2016 at 3:41

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.