fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <random>
  4. #include <ctime>
  5.  
  6. // Function to perform Fisher-Yates Shuffle in place
  7. void fisherYatesShuffle(std::vector<int>& arr) {
  8. // Initialize random number generator
  9. std::mt19937 rng(static_cast<long unsigned int>(time(0))); // Random seed based on time
  10.  
  11. // Loop through the array from last element to the second element
  12. for (int i = arr.size() - 1; i > 0; --i) {
  13. // Generate a random index between 0 and i
  14. std::uniform_int_distribution<int> dist(0, i);
  15. int j = dist(rng);
  16.  
  17. // Swap the elements at index i and index j
  18. std::swap(arr[i], arr[j]);
  19. }
  20. }
  21.  
  22. int main() {
  23. // Create a vector (array) of song IDs
  24. std::vector<int> arr = {10, 20, 30, 40, 50};
  25.  
  26. std::cout << "Original Array: ";
  27. for (int num : arr) {
  28. std::cout << num << " ";
  29. }
  30. std::cout << "\n";
  31.  
  32. // Shuffle the array using Fisher-Yates
  33. fisherYatesShuffle(arr);
  34.  
  35. std::cout << "Shuffled Array: ";
  36. for (int num : arr) {
  37. std::cout << num << " ";
  38. }
  39. std::cout << "\n";
  40.  
  41. return 0;
  42. }
  43.  
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
Original Array: 10 20 30 40 50 
Shuffled Array: 10 40 50 20 30