Implement rand5() Using rand7()

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

Example:

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

Approach

C++

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

int rand7()
{
    return rand() % 7 + 1;
}

int rand5()
{

    int x = rand7();
    if (x < 6)
        return x;
    return rand5();
}

int main()
{

    cout << rand5() << " ";
    return 0;
}


No comments:

Post a Comment