มีฟังก์ชัน rand7() สุ่มจำนวนเต็ม 1-7 สม่ำเสมอ เขียน rand10() สุ่ม 1-10 สม่ำเสมอ (ห้ามใช้ library random)
วิธีแก้ปัญหา (Rejection Sampling)
ใช้ rand7() 2 ครั้ง สร้างตัวเลข 0-48 (49 ค่า): (rand7()-1)×7 + (rand7()-1)
ตัดทิ้งค่า ≥ 40 (เหลือ 40 ค่า = 4×10) แล้ว mod 10 + 1
ตัวอย่างโค้ด C++
#include <bits/stdc++.h>
using namespace std;
int rand7() { return 1 + rand() % 7; }
class Solution {
public:
int rand10() {
int rand40 = 40;
while (rand40 >= 40) {
rand40 = (rand7() - 1) * 7 + (rand7() - 1);
}
return rand40 % 10 + 1;
}
};
int main() {
srand(time(NULL));
Solution ob;
cout << ob.rand10() << endl;
cout << ob.rand10() << endl;
cout << ob.rand10() << endl;
return 0;
}
Input
Call the function three times
Output
2 2 6