- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implement Rand10() Using Rand7() in C++
Suppose we have a function rand7 which generates a uniform random integer in the range 1 to 7, we have to write another function rand10 which generates a uniform random integer in the range 1 to 10. We cannot use some library function to generate random numbers.
Suppose we want two random numbers, so they may be [8,10].
To solve this, we will follow these steps −
- rand40 := 40
- while rand40 >= 40
- rand40 := (rand7() - 1) * 7 + (rand7() – 1)
- return rand40 mod 10 + 1
Let us see the following implementation to get better understanding −
Example
#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; } }; main(){ srand(time(NULL)); Solution ob; cout << (ob.rand10()) << endl; cout << (ob.rand10()) << endl; cout << (ob.rand10()) << endl; }
Input
Call the function three times
Output
2 2 6
Advertisements