/* This program is to ask the following questions about dummies taking planes:
* 100 people are waiting in line to take a plane with 100 seats. Normally, each of them will sit at the opposite number. However,
* The first person on the plane was a dumb. He randomly sat in a seat. When the next person got on the plane, if
* When a person is seated, he or she will randomly find a seat to sit down. Otherwise, he or she will sit down. Question: Last
* What is the probability that a person on the plane will sit in his seat ?? */
Using system;
Namespace stupid
{
Class Program
{
/// <Summary>
/// Used to save the computed results
/// </Summary>
Private double [] result;
Public Program ()
{
Result = new double [100];
}
/// <Summary>
/// Calculate the probability that the last person on the plane will sit in his seat
/// </Summary>
/// <Param name = "N"> </param>
/// <Returns> </returns>
Public double F (int n)
{
Double S = 0;
Double f = 0;
If (n = 2)
{
Return 0.5;
}
Else
{
For (INT I = 2; I <n; I ++)
{
If (result [I-1]! = 0)
S + = Result [I-1];
Else
{
F = f (I );
S + = F;
Result [I-1] = F;
}
}
Return (S + 1)/(double) (n );
}
}
/// <Summary>
/// Program entry
/// </Summary>
/// <Param name = "ARGs"> </param>
Static void main (string [] ARGs)
{
Double starttime, spendtime;
Starttime = system. datetime. Now. ticks;
Console. writeline ("result = {0}", new program (). F (100 ));
// Calculate the time required
Spendtime = (system. datetime. Now. ticks-starttime)/1000000.0;
Console. writeline ("calculation time: {0: F3}", spendtime );
Console. Read ();
}
}
}
Use the above algorithm (only an improvement to my original algorithm, of course, it would be better if I could change it to a non-recursive algorithm)
When N = 100, it takes about 0.1 seconds.
Here are my non-recursive algorithm answers to this question:
/// <Summary>
/// Calculate the probability that the last person on the plane will sit in his seat
/// Non-recursive algorithm
/// </Summary>
/// <Param name = "N"> </param>
/// <Returns> </returns>
Public double F2 (int n)
{
Double [] result = new double [n + 1];
Result [1] = 1;
For (INT I = 2; I <= N; I ++)
{
For (Int J = 1; j <I; j ++)
Result [I] + = Result [J];
Result [I]/= (double) I;
}
Return (n> 0? Result [N]: 0 );
}
I repeated dozens of operations on the two algorithms, and the results were consistent, a little unexpected.