Multiple enumerations:
Instance 1
There are 5 red balls and 4 white balls in the pocket. The probability of taking 3 balls out of a pocket randomly and taking out 1 red balls and 2 white balls
Copy Code code as follows:
<span style= "font-size:18px" > Srand ((unsigned) time (NULL));
int n = 0;
for (int i=0; i<100000; i++)
{
Char x[] = {1, 1, 1, 1, 1, 2, 2, 2, 2};//5 red ball with 5 1 for 4 white ball with 4 2
int a = 0; The number of red balls taken
int b = 0; The number of white balls taken
for (int j=0; j<3; j + +)//Take 3 balls to cycle 3 times
{
int k = rand ()% (9-J); Determining the scope of the subscript 9-j is the key
if (x[k]==1)
a++;
Else
b++;
X[K] = x[9-j-1]; Move the fetched number backward
}
if (a==1 && b==2) n++;//takes out 1 red Balls 2 white balls to count
}
printf ("Probability =%f\n", n/100000.0*100);</span>
Instance 2
Copy Code code as follows:
<span style= "font-size:18px" > #define N 30
......
int a[n];
Srand (Time (NULL));
int n = 0;
for (int k=0; k<10000; k++)
{
for (int i=0; i<n; i++)
A[i] = rand ()% 365;
bool tag = false; Assuming that there is no same
for (I=1; i<n; i++)
{
for (int j=0; j<i; j + +)
{
if (A[i]==a[j])
{
Tag = true;
Break
}
}
if (tag) break;
}
if (tag) n++;
}
printf ("%f\n", 1.0 * n/10000 * 100);
</SPAN>
Recursion:
A bag with a red ball m, white ball N. Now you want to remove the X ball from it. The probability of the number of red balls more than white balls
The following code solves the problem. Where y indicates the number of times the red ball appears at least.
This is equivalent to the problem in the previous article. If 30 balls are required, the number of red balls is greater than the number of white balls, which is equivalent to having at least 16 red balls removed.
Copy Code code as follows:
<span style= "font-size:18px" >/*
M: The number of red balls in the bag
N: The number of white balls in the bag
X: The number that needs to be removed
Y: The number of times the red ball appears at least
*/
Double Pro (int m, int n, int x, int y)
{
if (y>x) return 0;
if (y==0) return 1; No requirement for Y
if (y>m) return 0;
if (x-n>y) return 1; All the white balls out, the rest is red ball red ball than at least take out more, the probability of 1
Double P1 = Pro (m-1,n,x-1,y-1);
Double P2 = Pro (m,n-1,x-1,y);
Return (double) m/(m+n) * p1 + (double) n/(m+n) * P2;
}</span>