Monday, April 23, 2012

Monkey Typing

一道题目:一个打字机上有26个字母键,一个猴子每秒钟随意打一个键,问它第一次打出 abc 这个字符串的时间的期望是多少。

@alpha = ('a'..'z');

open (OUT,">monkey_out.txt") or die "could not write to the output file" ;

sub monkey_type
{ @words=();
$sta=1;
while(1)
{
$current=$alpha[rand 26];
push(@words,$current);
if($words[-3] eq "a" && $words[-2] eq "b" && $words[-1] eq "c" )
{
print OUT "$sta\n";
last;
}
$sta++;
}
}


# Set the stimulation cycles here ;
for($i=1;$i<=50;$i++ )
{
&monkey_type;
print "$i\n";
}