- 只要我们可以从 n 个数中随机选出 1 到 n 个数,反复进行这种运算,直到剩下最后一个数即可。
- 我们可以调用 n 次给定函数,生成 n 个 1 到 5 之间的随机数,选取最大数所在位置即可满足以上要求。
- 例如
- 初始的 7 个数 [1,2,3,4,5,6,7].
- 7 个 1 到 5 的随机数 [5, 3,1,4,2,5,5]
- 那么我们保留下[1,6,7],
- 3 个1 到 5 的随机数[2,4,1]
- 那么我们保留下[6]
- 6 就是我们这次生成的随机数。
- http://bylijinnan.iteye.com/blog/1460963
-
- /* solution 2:
- * return 1~7 randomly
- */
- public int rand7(){
- List<Integer> list=new ArrayList<Integer>();
- for(int i=1;i<=7;i++){
- list.add(i);
- }
- return rand7Help(list);
- }
- public int rand7Help(List<Integer> list){
- if(list==null || list.size()==0){
- return -1;
- }
- if(list.size()==1){
- return list.get(0);
- }
- int n=list.size();
- int[] nRand5=new int[n];
- int max=0;
- for(int i=0;i<n;i++){
- int x=rand5();
- if(x>max){
- max=x;
- }
- nRand5[i]=x;
- }
- List<Integer> newList=new ArrayList<Integer>();
- for(int i=0;i<n;i++){
- if(nRand5[i]==max){
- newList.add(list.get(i));
- }
- }
- return rand7Help(newList);
- }
- public int rand5(){
- return new Random().nextInt(5)+1;
- }
- }
解法二:假设rand5能随机生成1~5的5个数(均等概率),利用rand5生成rand7() 1~7(均等概率)
1. 利用rand5求出rand2(),当rand5生成的数大于2时,一直循环,直到它生成的数为1或者2,且生成1和2的概率均为1/2,因为生成1和生成2的概率是相等的。
2. 利用rand2生成0和1(减1即可),连续使用三次,共有8种可能(二进制表示):000 001 010 011 100 101 110 111,当生成的数为000时,重新计算,这样就可以得到1~7范围内的数,且概率是均等的。
- #include <iostream>
- #include <math.h>
- using namespace std;
- int rand5()
- {
- return rand()%5+1;
- }
- int rand2()
- {
- int temp;
- do
- {
- temp = rand5();
- } while (temp > 2);
- return temp;
- }
- int rand7()
- {
- int temp;
- do
- {
- temp = (rand2()-1)<<2;
- temp += (rand2()-1)<<1;
- temp += rand2()-1;
- } while (temp == 0);
- return temp;
- }
- int main(int, char **)
- {
- int num;
- cout << "输入总生成数:";
- cin >> num;
- int c1, c2, c3, c4, c5, c6, c7;
- c1 = c2 = c3 = c4 = c5 = c6 = c7 = 0;
- for (int i = 0; i < num; i++)
- {
- int temp = rand7();
- switch (temp)
- {
- case 1:
- c1++;
- break;
- case 2:
- c2++;
- break;
- case 3:
- c3++;
- break;
- case 4:
- c4++;
- break;
- case 5:
- c5++;
- break;
- case 6:
- c6++;
- break;
- case 7:
- c7++;
- }
- //cout << temp << "\t";
- }
- cout << endl;
- cout << "生成1的个数占总生成数的:" << (double)c1/num*100 << "%" << endl;
- cout << "生成2的个数占总生成数的:" << (double)c2/num*100 << "%" << endl;
- cout << "生成3的个数占总生成数的:" << (double)c3/num*100 << "%" << endl;
- cout << "生成4的个数占总生成数的:" << (double)c4/num*100 << "%" << endl;
- cout << "生成5的个数占总生成数的:" << (double)c5/num*100 << "%" << endl;
- cout << "生成6的个数占总生成数的:" << (double)c6/num*100 << "%" << endl;
- cout << "生成7的个数占总生成数的:" << (double)c7/num*100 << "%" << endl;
- return 0;
- }
给定能随机生成整数1到5的函数,写出能随机生成整数1到7的函数
最新推荐文章于 2022-10-17 22:15:09 发布