使用1-5隨機數生成器產生1-7的隨機數(Google Technical Interview)

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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章