Implement rand7() Using rand5()

Using a function rand5() that returns an integer from 1 to 5 (inclusive) with uniform probability, implement a function rand7() that returns an integer from 1 to 7 (inclusive).

Example:

Output: 2  //answer may be different but answer lies between [1 ,7] inclusive

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

int rand5()
{
    return rand() % 5 + 1;
}

int rand7()
{
    int x = 5 * rand5() + rand5() - 5;
    if (x < 22)
    {
        return x % 7 + 1;
    }
    return rand7();
}
int main()
{

    cout << rand7() << " ";

    return 0;
}


No comments:

Post a Comment