View plainprint?
/**
* If a rand7 () function is known, a random natural number ranging from 1 to 7 is returned. This rand7 () is used to construct rand10 () random 1 ~ 10.
*/
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Namespace ConsoleApplication1
{
Class Program
{
Static void Main (string [] args)
{
Rand10 rand10 = Rand10.GetInstance ();
Long total = 9999999;
// Record 1 ~ The number of times the number of 10 is generated.
Int [] numArray = new int [10];
For (long I = 0; I <total; I ++)
{
Int randomNumber = rand10.Next ();
NumArray [randomNumber-1] ++;
}
// Print the probability of each number.
For (int I = 0; I <numArray. Length; I ++)
{
Console. WriteLine (string. Format ("the probability of generating {0} is: {1:0. 00000}", I + 1, (Double) numArray [I]/total ));
}
Console. ReadLine ();
}
}
// 1 ~ 7 random number generation class
Public class Rand7
{
Private static Rand7 _ rand7;
Private readonly Random _ random = new Random ();
Private Rand7 ()
{
}
Public static Rand7 GetInstance ()
{
If (_ rand7 = null)
{
_ Rand7 = new Rand7 ();
}
Return _ rand7;
}
// Obtain the random number
Public int Next ()
{
Return _ random. Next (1, 8 );
}
}
// 1 ~ Random Number Generation class of 10
Public class Rand10
{
Private static Rand10 rand10;
Private Rand7 _ rand7 = Rand7.GetInstance ();
Private Rand10 ()
{
}
Public static Rand10 GetInstance ()
{
If (rand10 = null)
{
Rand10 = new Rand10 ();
}
Return rand10;
}
// Obtain the random number
Public int Next ()
{
Int num;
// Uniformly generate 1, 2, 3, 4, and 5
While (true)
{
Num = _ rand7.Next ();
If (num <= 5)
Break;
}
While (true)
{
Int n = _ rand7.Next ();
If (n = 4)
Continue;
// Numbers with n greater than 4 are 5, 6, and 7. The probability is even because they are generated by Rand7.
If (n> 4)
// Because num can only be set to values 1, 2, 3, 4, and 5, with even probability, num * 2 can be set to 2, 4, 6, 8, and 10 with even probability.
Num * = 2;
// Numbers with n less than 4 include numbers 1, 2, and 3. the probability is even because they are generated by Rand7.
Else
// Because num can only be set to values 1, 2, 3, 4, and 5, and the probability of values is even. num * 2-1 can be set to 1, 3, 5, 7, and 9, and the probability is even.
Num = num * 2-1;
Break;
}
Return num;
}
}
}
Author: "cangkuaimanle's column"