我必须写一个实验室,计算10,000个硬币翻转中最长的头尾序列。我似乎无法弄清楚如何做到这一点。提示?
答案 0 :(得分:2)
这里有一些伪代码:
biggest_yet = 0;
counter = 0;
if this_flip = last_flip
counter++;
if counter > biggest_yet
biggest_yet = counter;
end if
end if
答案 1 :(得分:2)
如果您需要跟踪最长的头部和尾部序列,这里有一些伪代码。
longestTail = 0;
longestHead = 0;
counter = 0;
if (flip == lastFlip)
counter++;
if (flip.isTailFlip AND counter > longestTail)
longestTail = counter;
else if (counter > longestHead)
longestHead = counter;
end if
else
counter = 1;
end if
请注意第一次翻转flip = lastFlip
评估为false
。我省略了输出。希望能帮助到你。如果还有其他问题可以随意提问。 ;)
答案 2 :(得分:1)
以下是您可能实施的算法大纲:
希望有所帮助! :)
答案 3 :(得分:1)
练习的重点可能是提高效率 -
也许是在最大的头或尾的时候退出 大于剩下的投掷数量。运行= window.Run || {};
Run.countmaxflips=function(n){
n= n || 10000;
var str= '', L= 0, temp, tem, run, max= 0,
toss= [[0, 0], [0, 0]];
while(L<n){
temp= Math.round(Math.random());
++toss[temp][0];
if(tem!=undefined && tem!== temp){
run= toss[tem][0];
if(run> toss[tem][1]) toss[tem][1]= run;
toss[tem][0]= 0;
if(max<run) max= run;
if(L+max >n)L= n;
}
tem= temp;
++L;
}
if(toss[0][1]=== max) str= max+' tails in a row ';
if(toss[1][1]=== max){
if(str) str+= ' and ';
str+= max+' heads in a row';
}
return str;
}
Run.countmaxflips(10000)
/* returned values: (Strings)
11 tails in a row and 11 heads in a row
14 heads in a row
15 tails in a row
17 heads in a row
12 heads in a row
12 tails in a row
12 tails in a row
14 heads in a row
11 tails in a row
14 tails in a row
15 tails in a row
11 tails in a row and 11 heads in a row
13 tails in a row and 13 heads in a row
13 tails in a row and 13 heads in a row
15 tails in a row
13 heads in a row
12 tails in a row
11 tails in a row and 11 heads in a row
15 heads in a row
13 tails in a row
*/