I'm trying to shuffle a ArrayList of Integers in a random fashion. I have came up with the code below. However, I am doubtful that this is the correct way to do it. I have read somewhere that for for(int i = list.size(); i >= 1; i--)
in:
public static void shuffling(List<?> list, Random rnd){
for(int i = list.size(); i >= 1; i--){
swap(list, i - 1, rnd.nextInt(i));
}
}
It should be written instead as:
for(int i = list.size(); i > 1; i--)
But if I chose to write it as i > 1
instead of i >= 1
, aren't I neglecting the first item in the ArrayList? Anyone have any suggestions on what is the correct way to go about this problem?
My Code:
public class TheCollectionInterface {
public static <E> void swap(List<E> a, int i, int j){
E temp = a.get(i);
a.set(i, a.get(j));
a.set(j, temp);
}
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 void main(String[] args) {
List<Integer> li1 = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7,8,9));
Random r1 = new Random();
TheCollectionInterface.shuffling(li1, r1);
System.out.println(li1);
}
}