ที่นี่เราจะดู shuffle และ random_shuffle ใน C++ มาดู random_shuffle ก่อน ใช้จัดเรียงสมาชิกในช่วง [left, right) แบบสุ่ม ฟังก์ชันนี้สลับตำแหน่งแต่ละสมาชิกกับตำแหน่งที่สุ่มมา เราสามารถส่งฟังก์ชันสุ่มตัวเลขเข้าไปได้ ถ้าไม่ส่ง จะใช้ฟังก์ชันสุ่มของมันเอง
ตัวอย่าง random_shuffle
#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()); // ใช้ฟังก์ชันสุ่ม built-in
cout << "arr elements:";
for (vector<int>::iterator i = arr.begin(); i != arr.end(); ++i)
cout << ' ' << *i;
cout << endl;
// ใช้ myRandomGenerator
random_shuffle(arr.begin(), arr.end(), myRandomGenerator);
cout << "arr elements:";
for (vector<int>::iterator i = arr.begin(); i != arr.end(); ++i)
cout << ' ' << *i;
cout << endl;
}
ผลลัพธ์
arr elements: 5 14 15 6 3 16 13 12 10 2 4 1 17 9 18 11 7 8 19 arr elements: 8 10 5 6 14 1 15 3 19 16 13 18 7 9 4 12 11 17 2
ต่อมา shuffle() ใช้จัดเรียงสมาชิกในช่วง [left, right) แบบสุ่ม เช่นกัน รับ uniform random number generator หนึ่งตัว
ตัวอย่าง shuffle
#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 elements:";
for (vector<int>::iterator i = arr.begin(); i != arr.end(); ++i)
cout << ' ' << *i;
cout << endl;
}
ผลลัพธ์
arr elements: 19 7 5 6 12 4 13 3 1 17 11 14 18 2 8 15 9 10 16
ความแตกต่างเดียวระหว่าง random_shuffle() และ shuffle() คือ random_shuffle() ใช้ rand() สร้างดัชนีสุ่ม ส่วน shuffle() ใช้ uniform random number generator ถ้าเราส่ง uniform random number generator เข้า random_shuffle() จะได้ผลลัพธ์แบบเดียวกัน