ที่นี่เราจะเห็น Shuffle และ random_shuffle ใน C++ ฟังก์ชันเหล่านี้ใช้เพื่อสับเปลี่ยนอิลิเมนต์อาร์เรย์ใน C++ เราสามารถใช้เวกเตอร์แทนอาร์เรย์ได้ การใช้งานก็คล้ายคลึงกัน ให้เราดู random_shuffle() ก่อน ใช้เพื่อสุ่มจัดองค์ประกอบใหม่ในช่วง [ซ้าย, ขวา) ฟังก์ชันนี้จะสุ่มสลับตำแหน่งของแต่ละองค์ประกอบด้วยตำแหน่งของตำแหน่งที่เลือกแบบสุ่ม
เราสามารถจัดเตรียมฟังก์ชันตัวสร้างแบบสุ่มเพื่อบอกว่าองค์ประกอบใดจะถูกนำไปใช้ในทุกกรณี หากเราไม่ได้จัดเตรียมไว้ ระบบจะใช้ฟังก์ชันตัวสร้างแบบสุ่มของตัวเอง
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
int myRandomGenerator(int j) {
return rand() % j;
}
main() {
srand(unsigned(time(0)));
vector<int> arr;
for (int j = 1; j < 20; ++j) //generate 20 numbers and add them into vector arr
arr.push_back(j);
random_shuffle(arr.begin(), arr.end()); //use inbuilt random function to shuffle
cout << "arr elements:";
for (vector<int>::iterator i = arr.begin(); i != arr.end(); ++i)
cout << ' ' << *i;
cout << endl;
// using 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() คืออะไร นอกจากนี้ยังใช้เพื่อจัดเรียงองค์ประกอบใหม่ในช่วง [ซ้าย, ขวา) สุ่ม ต้องใช้เครื่องกำเนิดตัวเลขสุ่มหนึ่งชุด
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
main() {
vector<int> arr;
unsigned seed = 0;
for (int j = 1; j < 20; ++j) //generate 20 numbers and add them into vector arr
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() ใช้ตัวสร้างตัวเลขสุ่มที่เหมือนกัน แม้ว่าถ้าเราส่งตัวสร้างตัวเลขสุ่มแบบสม่ำเสมอด้วย random_shuffle() ก็จะสร้างผลลัพธ์บางอย่าง