Implement rand3 ( ) using rand2 ( ) | C ++ Program to print 0 , 1 or 2 with equal probability ; Random Function to that returns 0 or 1 with equal probability ; rand ( ) function will generate odd or even number with equal probability . If rand ( ) generates odd number , the function will return 1 else it will return 0. ; Random Function to that returns 0 , 1 or 2 with equal probability 1 with 75 % ; returns 0 , 1 , 2 or 3 with 25 % probability ; Driver code to test above functions
#include <iostream> NEW_LINE using namespace std ; int rand2 ( ) { return rand ( ) & 1 ; } int rand3 ( ) { int r = 2 * rand2 ( ) + rand2 ( ) ; if ( r < 3 ) return r ; return rand3 ( ) ; } int main ( ) { srand ( time ( NULL ) ) ; for ( int i = 0 ; i < 100 ; i ++ ) cout << rand3 ( ) ; return 0 ; }