您的位置:首页 > 编程语言 > Go语言

使用1-5随机数生成器产生1-7的随机数(Google Technical Interview)

2013-05-15 08:20 253 查看
Problem

Generate random between 1..7(Google Technical Interview).Write a method to generate a random number between 1 and 7, given a method that generates a random number between 1 and 5 (i. e. , implement rand7() using rand5()).

Solution
#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

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

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

int rand7_use_rand5()
{
while(true){
int n = (rand5() - 1) + (rand5()-1) * 5;
if(n < 21){
return n % 7 + 1;
}
}
}

int main(int argc, char* argv[])
{
srand((unsigned)time( NULL ));
int count[7];

for(int i = 0; i < 7; i ++){
count[i] = 0;
}

for(int i = 0; i < 21000000; i ++){
int n = rand7_use_rand5();
count[n-1] ++;
}
cout << endl;

for(int i = 0; i < 7; i ++){
cout << "Generate " << i + 1 << " times " << count[i] << endl;
}

return 0;
}

Output

Generate 1 times 3003430
Generate 2 times 2999505
Generate 3 times 2999024
Generate 4 times 3000855
Generate 5 times 2998199
Generate 6 times 3001455
Generate 7 times 2997532
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 随机数 Google
相关文章推荐