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);
    }
}
\$\endgroup\$
2
  • \$\begingroup\$ Did you consider Collections.shuffle()? \$\endgroup\$
    – Legato
    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\$
    – Thor
    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.

\$\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\$
    – Thor
    Mar 12, 2016 at 3:41

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.