码迷,mamicode.com
首页 > 其他好文 > 详细

算法题--等概率产生0和1(有扩展)

时间:2014-08-07 13:05:00      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   for   art   

 1 #include <iostream>
 2 #include <string>
 3 #include <memory.h>
 4 #include <vector>
 5 #include <sstream>
 6 #include <math.h>
 7 #include <climits>
 8 #include <algorithm>
 9 #include <cstdlib>
10 using namespace std;
11 
12 const int k = 20;
13 const int n = 500;
14 int rand_01()
15 {
16     int i1 = 0;
17     int i2 = 0;
18     while(i1 == i2)
19     {
20         i1 = rand();
21         i2 = rand();
22     }
23     if(i1 == 1)
24         return 1;
25     else
26         return 0;
27     return -1;
28 }
29 
30 int rand_1N()
31 {
32     int res = 0;
33     int i;
34     for(i = 0 ; i < k;++i)
35     {
36         if(rand_01() == 1)
37         {
38             res |= (1<<i);
39         }
40     }
41     if(res > n || res==0)
42         return rand_1N();
43     return res;
44 }
45 
46 int main()
47 {
48     cout<<rand_1N()<<endl;
49     return 0;
50 }

http://blog.csdn.net/iloveyin/article/details/8122049

原来链接里的代码存在问题,可能会一直产生0,所以加个判断

由于各个位都是独立的,所以可以产生0~2^k之间的数.

算法题--等概率产生0和1(有扩展),布布扣,bubuko.com

算法题--等概率产生0和1(有扩展)

标签:style   blog   http   color   os   io   for   art   

原文地址:http://www.cnblogs.com/cane/p/3896793.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!