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

 Live Demo

#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

Updated on: 02-May-2020

269 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements