C++ cung cấp hai hàm xáo trộn: random_shuffle (cũ, C++11, loại bỏ C++17) và shuffle (C++11, khuyến nghị). Cả hai sắp xếp ngẫu nhiên các phần tử trong khoảng [first, last).
1. random_shuffle
Sử dụng rand() nội bộ hoặc hàm generator tùy chỉnh.
#include <bits/stdc++.h>
using namespace std;
int myRandomGenerator(int j) { return rand() % j; }
int main() {
srand(unsigned(time(0)));
vector<int> arr;
for (int j = 1; j < 20; ++j) arr.push_back(j);
random_shuffle(arr.begin(), arr.end()); // dùng rand()
cout << "arr (rand):";
for (int x : arr) cout << ' ' << x;
cout << endl;
random_shuffle(arr.begin(), arr.end(), myRandomGenerator); // dùng generator tùy chỉnh
cout << "arr (custom):";
for (int x : arr) cout << ' ' << x;
return 0;
}
2. shuffle (Khuyến nghị)
Sử dụng Uniform Random Number Generator (như default_random_engine, mt19937).
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> arr;
unsigned seed = 0;
for (int j = 1; j < 20; ++j) arr.push_back(j);
shuffle(arr.begin(), arr.end(), default_random_engine(seed));
cout << "arr (shuffle):";
for (int x : arr) cout << ' ' << x;
return 0;
}
Kết quả mẫu
arr (rand): 5 14 15 6 3 16 13 12 10 2 4 1 17 9 18 11 7 8 19 arr (custom): 8 10 5 6 14 1 15 3 19 16 13 18 7 9 4 12 11 17 2 arr (shuffle): 19 7 5 6 12 4 13 3 1 17 11 14 18 2 8 15 9 10 16
Khác biệt: random_shuffle dùng rand() (kém ngẫu nhiên), shuffle dùng URNG chất lượng cao hơn. Từ C++17, random_shuffle bị loại bỏ.