Problem
Given a function foo()
, that returns an integer between 1 and 5 (inclusive) with equal probability. Write a function using foo()
that returns an integer between 1 and 7 (inclusive) with equal probability.
Solution
Randomize() return 5*foo() + foo() - 5
Approach 1
Now, Randomize()
generates integers 1 to 25 with equal probability ie. 1/25 (each). So our solution is:
return N
, only if N >= 1 && N < 8
Randomize1() N = 5*foo() + foo() - 5 if N >= 1 && N < 8: return N
Approach 2
Since, Randomize()
generates integers 1 to 25 with equal probability ie. 1/25 (each). So our solution is:(N%7) + 1
, only if N < 22
,
otherwise 2, 3, 4 and 5 will have more probability (4/7 each).
Randomize2() N = 5*foo() + foo() - 5 if N < 22: return (N%7) + 1
Code Implementation
//
// main.cpp
// Custom Randomize
//
// Created by Himanshu on 27/11/22.
//
#include <iostream>
using namespace std;
int randomize() {
int x = rand()%5 + 1;
return x;
}
int customRandomize() {
int N = 5*randomize() + randomize() - 5;
while (N > 7) {
N = 5*randomize() + randomize() - 5;
}
return N;
}
//This method is slightly more efficient
int customRandomize2 () {
int N = 5*randomize() + randomize() - 5;
while (N > 21) {
N = 5*randomize() + randomize() - 5;
}
return ((N%7) + 1);
}
int main () {
int x, y;
cout<<"Randomly generated integers between 1 and 7:"<<endl;
for (int i=0; i<5; i++) {
x = customRandomize();
cout<<x<<endl;
y = customRandomize2();
cout<<y<<endl;
}
return 0;
}
Output
Randomly generated integers between 1 and 7: 5 4 2 6 1 4 6 3 7 2
Here’s a working example: Custom Randomize