×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Volker Lenhardt
Added: Feb 13, 2022 11:07 AM
Modified: Aug 4, 2022 5:47 PM
Views: 429
  1. // Collections.shuffle(...)
  2. // Arrays.asList() only works with an array of objects.
  3. // Autoboxing doesn't work with generic types.
  4. // So you can't use Collections.shuffle(...) with primitives.
  5. Integer[] intArray = { 1, 2, 3, 4, 5, 6, 7 };
  6. List<Integer> intList = Arrays.asList(intArray);
  7. Collections.shuffle(intList);
  8. intList.toArray(intArray);
  9.  
  10. // Alternative: Fisher-Yates shuffle
  11. // Works with arrays of any type.
  12. // For one position after the other a randomly
  13. // chosen element is taken out of the remaining ones.
  14. // The procedure starts at the end of the array
  15. // and ends at position 1, because the zero position
  16. // would leave no choice but 0.
  17. Random rand = new Random();
  18. int index, temp;
  19. int len = intArray.length;
  20. for (int i = len - 1; i > 0; i--) {
  21.     index = rand.nextInt(i + 1);
  22.     temp = intArray[index];
  23.     intArray[index] = intArray[i];
  24.     intArray[i] = temp;
  25. }
  26.