Reputation:
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);
}
}
Upvotes: 1
Views: 86
Reputation: 60788
There's Collections.shuffle
, of course, if you're trying not to roll your own.
Upvotes: -1
Reputation: 75062
When i = 1
in this loop, The only element to choose is the 0th element and swapping 0th element with 0th element is trivial and will have no effect. Therefore, you don't need to enter the loop with i = 1
and you can write i > 1
as the condition.
Upvotes: 2