Extended random number

random number generation

(1) System functions such as random can be used, the constructor rand 15: in the range of [1,5], a uniformly distributed random function

 (2) Random cannot be used, only rand112 is constructed based on rand15: in the range of [1,12], a random function of uniform decibels

(3) Function randint26: A random function that generates an integer with equal probability in the range of [2, 3, 4, 5].

(4) Random cannot be used, only randint26 is given to construct randint212: a random function that generates an integer with equal probability in the range of [2,...11,12].

 

For a random function with a fixed range, such as rand15, if the random number in the range of 1-12 is extended

can do

(rand15-1)*rand15+rand15 can represent random numbers within 1-25, the principle is annotated in the code

 

//
//  main.cpp
//  xxxx
//
//  Created by 小康 on 26/04/2018.
//  Copyright © 2018 小康. All rights reserved.
//
#include <iostream>
#include <random>

using namespace std;

int rand15()
{
    // random number between 1 and 5 
    return  1 +rand() % 5 ;
}
int rand112()
{
    // (rand15()-1)*5 : 0 5 10 15 25 five random numbers p1=1/5
     // rand15() 1 2 3 4 5 five random numbers p2 = 1/5
     // any of them Add up to get a random number between 1 and 25 p = p1*p2 = 1/25
    // and then take an 
    int less than or equal to 12 x= 0 ;
     while ( true )
    {
        x=(rand15()-1)*5+rand15();
        if(x<=12) break;
    }
    return x;
 
}
int rand26()
{
    // random number between 2 and 5 
    int x;
     while ( true )
    {
        x = 1 +rand()% 5 ;
         // If = 1, continue random 
        if (x!= 1 )
             break ;
        
    }
    return x;
}
int rand212()
{
  // The same principle as above 
    int x = 0 ;
     while ( true )
    {
        x=(rand26()-2)*4+rand26()-1;
        if(x<=12&&x>=2)
            break;
    }
    return x;
}
intmain ()
{
     srand((unsigned)time(NULL));
    for(int i=1;i<=100;i++)
    {
        cout<<rand15()<<" "<<rand112()<<endl;
        cout<<rand26()<<" "<<rand212()<<endl;
        cout<<endl;
    }
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324914746&siteId=291194637