Skip to content

Instantly share code, notes, and snippets.

@dqtweb
Created August 20, 2024 01:46
Show Gist options
  • Save dqtweb/56c596c8acbc4053e836cd560890494b to your computer and use it in GitHub Desktop.
Save dqtweb/56c596c8acbc4053e836cd560890494b to your computer and use it in GitHub Desktop.
Fisher-Yates algorithm (or Knuth Shuffle)
public static List<Object> shuffleList(List<Object> list) {
Random rand = new Random();
// convert to array
Object[] array = list.toArray();
for (int i = array.length - 1; i > 0; i--) {
// generate random number in range 0 to i
int j = rand.nextInt(i + 1);
// swap array[i] with array[j]
Object temp = array[i];
array[i] = array[j];
array[j] = temp;
}
// convert back to list
return Arrays.asList(array);
}
@dqtweb
Copy link
Author

dqtweb commented Aug 20, 2024

public static void main(String[] args) {
        List<Object> list = Arrays.asList("1", "2", "3", "4", "5");
        list = shuffleList(list);
        for (Object obj : list) {
            System.out.print(obj + " ");
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment