使用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 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
相关文章推荐
- 使用C++如何产生32位随机数
- 随机数产生转换-根据(1,5)随机数生成器,生成(1,7)之内的随机数
- C语言中用于产生随机数的函数使用方法总结
- .net中使用Random()产生一个随机数
- 随机数产生转换-根据(1,5)随机数生成器,生成(1,7)之内的随机数
- 设计一个类,该类中有一个方法,该方法使用Random类随机产生10个三位数字(如636)的随机数,并把产生的10个随机数存入数组中。然后在另一个类中输出这10个数
- 使用C语言产生正太分布的随机数之四
- 随机数产生转换-根据(1,5)随机数生成器,生成(1,7)之内的随机数
- 产生随机数 rand() 和 srand() 函数的使用
- 初识c# 随机数产生及库类中常用字符串函数使用
- 使用C++产生32位随机数
- 使用C语言产生正太分布的随机数之问答篇
- 【原创】开源Math.NET基础数学类库使用(13)C#实现其他随机数生成器
- 给定1-a的随机数生成器,产生1-b的随机数生成器
- 使用均匀分布随机数产生器构造任意分布的随机数产生器
- sort方法的使用、随机数的产生
- 设计程序,单击【随机数】按钮,使用Math对象的random函数产生一个0-100之间(含0-100)的随机整数,并在对话框中显示,如下图。单击【计算】按钮,计算该随机数的平方、平方根和自然对数,保留两位小数,并在对话框中显示,如下图。
- java7新特性——使用ThreadLocalRandom产生并发随机数
- oracle中使用DBMS_RANDOM去产生随机数
- 数组------写一个程序,产生25个随机数,对每个随机值,使用if-else 分类为大于、小于、等于