Skip to content

Instantly share code, notes, and snippets.

@ivycheung1208
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivycheung1208/e0651a09a5a03784d28f to your computer and use it in GitHub Desktop.
Save ivycheung1208/e0651a09a5a03784d28f to your computer and use it in GitHub Desktop.
CC150 17.11
/* CC150 17.11 */
// implement a method rand7() given rand5()
#include <iostream>
#include <cstdlib>
#include <map>
#define N 10000
using namespace std;
int rand5() { return rand() % 5; }
// use 5 * rand5()
int rand7()
{
while (1) {
int n = 5 * rand5() + rand5(); // evenly between [0, 24]
if (n < 21)
return n % 7;
}
}
// use 2 * rand5()
int rand7_2()
{
while (1) {
int n1 = 2 * rand5(); // {0, 2, 4, 6, 8]}
int n2 = rand5();
if (n2 < 4) { // disgard one extra value
int n = n1 + n2 % 2; // evenly between [0, 9]
if (n < 7)
return n;
}
}
}
// use 4 * rand5()
int rand7_4()
{
while (1) {
int n1 = 4 * rand5(); // {0, 4, 8, 12, 16}
int n2 = rand5();
if (n2 < 4) {
int n = n1 + n2; // evenly between [0, 19]
if (n < 14)
return n % 7;
}
}
}
int main()
{
map<int, int> prob;
for (int i = 0; i != 7; ++i)
prob[i] = 0;
for (int i = 0; i != N; ++i)
++prob[rand7()];
int count = 0;
for (int i = 0; i != 7; ++i) {
count += prob[i];
cout << prob[i] << endl;
}
cout << count << endl;
return 0;
}
5X:
1353
1463
1447
1427
1474
1451
1385
10000
2X:
1376
1459
1421
1417
1418
1421
1488
10000
4X:
1480
1441
1466
1380
1456
1381
1396
10000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment