亚麻 how to generate random integer

面试亚麻 的时候就败在这里。

每个数字生成的概率是相等的。 

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <set>

//how to generate the random number in [a, b], (a,b] or [a,b).
using namespace std;
int main() {
    int N= 100;
    
    int a = 0 ; int b = 1000;//[a,b]
    int cnt =0;
    set< int> res;
    // set seed by using time. if do not call srand to set seed, output of rand() will be same at each runing. you can comment this clause to test.
    srand ((unsigned int)time(nullptr));
    while ( cnt < N){
        
        if (res.size () >= b) { cout<< "done " << endl; break;}
        
        // rand () return a random number less than INT_MAX, so if you want generate specific range, you should use % operator.
        // case one :  (rand() % (b-a))+ a; the range is [a, b);
        // case two : (rand() % (b-a)+1)+ a; the range is [a, b];
        // case three: (rand() % (b-a))+ a+1; the range is (a, b];
        int val = (rand() % (b-a))+ a;
        
        // if collision, recall rand. since use % to generate the random number, so probility of the collision is very high.
        if (res.find(val) != res.end()) continue ;// { cout<< "collision " << endl; return 0;}
        
        res.insert(val);
        cout << val << " ";
        
    }
    
//    for (auto& e : res)
//        cout << e << " ";
    return 0;
}

 

posted @ 2018-01-28 04:54  HisonSanDiego  阅读(102)  评论(0编辑  收藏  举报