Stats

Popular Posts

Followers

Mathematica 教學:Project Euler problem 213

戴忠淵 於 2012年3月17日星期六 上午12:10 發表

Q: A 30 x 30 grid of squares contains 900 fleas, initially one flea per square. When a bell is rung, each flea jumps to an adjacent square at random (usually 4 possibilities, except for fleas on the edge of the grid or at the corners).

What is the expected number of unoccupied squares after 50 rings of the bell? Give your answer rounded to six decimal places.




next[i_,j_]:=Block[{temp},
temp=Table[0,{x,30},{y,30}];
Which[
i==1&&j==1,temp[[1,2]]=temp[[2,1]]=1/2,
i==1&&2<=j<=29,temp[[1,j-1]]=temp[[1,j+1]]=temp[[2,j]]=1/3,
i==1&&j==30,temp[[1,29]]=temp[[2,30]]=1/2,
2<=i<=29&&2<=j<=29,temp[[i-1,j]]=temp[[i+1,j]]=temp[[i,j-1]]=temp[[i,j+1]]=1/4,
2<=i<=29&&j==1,temp[[i-1,1]]=temp[[i+1,1]]=temp[[i,2]]=1/3,
2<=i<=29&&j==30,temp[[i-1,30]]=temp[[i+1,30]]=temp[[i,29]]=1/3,
i==30&&j==1,temp[[29,1]]=temp[[30,2]]=1/2,
i==30&&2<=j<=29,temp[[30,j-1]]=temp[[30,j+1]]=temp[[29,j]]=1/3,
i==30&&j==30,temp[[29,30]]=temp[[30,29]]=1/2
];
N@Flatten[Table[temp[[x,y]],{x,30},{y,30}]]
]

(*轉移矩陣*)

tm=next@@@Flatten[Table[{i,j},{i,30},{j,30}],1];

ans213=Total[Times@@@(Table[1,{i,900},{j,900}]-Nest[#.tm&,tm,50])]


nextsquare[i_,j_]:=
Which[
i==1&&j==1,RandomChoice[{{1,2},{2,1}}],
i==1&&2<=j<=29,RandomChoice[{{1,j-1},{1,j+1},{2,j}}],
i==1&&j==30,RandomChoice[{{1,29},{2,30}}],
2<=i<=29&&2<=j<=29,RandomChoice[{{i-1,j},{i+1,j},{i,j-1},{i,j+1}}],
2<=i<=29&&j==1,RandomChoice[{{i-1,1},{i+1,1},{i,2}}],
2<=i<=29&&j==30,RandomChoice[{{i-1,30},{i+1,30},{i,29}}],
i==30&&j==1,RandomChoice[{{29,1},{30,2}}],
i==30&&2<=j<=29,RandomChoice[{{30,j-1},{30,j+1},{29,j}}],
i==30&&j==30,RandomChoice[{{29,30},{30,29}}]
]

(* 所有方格座標 *)

flea=Flatten[Table[{i,j},{i,30},{j,30}],1];

DistributeDefinitions[nextsquare,flea];

(* 計算每隻跳蚤在50響鐘聲之後的座標,之後取餘集,實驗1000次,最後求平均 *)

Mean@ParallelTable[Length[Complement[flea,
Table[Nest[nextsquare@@#&,z,50],{z,flea}]]],{100}]


Tags:

讀者回應 ( 0 意見 )

發佈留言

Please leave your name and tell me what you thought about this site. Comments, suggestions and views are welcomed.

如果這篇文章對你有幫助,那請留個訊息給我~