ゲーム:
5 つのセクションに分割されたボックスがあります。ボックスの中にマウスが座っています。ボックスの近くに座っている猫。
毎ターン、猫は足をセクションに置きます。
1) ねずみがいる部分に猫が前足を置いたらゲームオーバー
2) そうでなければ、ねずみは猫の手の下の部分を含めて隣の部分に移動
する最小手数 (平均) で勝ちます。
チェーン - 猫の一連の動きを周期的に繰り返します。
次の関数は、特定のチェーンで勝つまでの平均移動回数を返します。
public static double computePerformanceForChain(String chain)
{
final int iterationsCount = 10000;
int catPos, mousePos,steps=0;
Random random = new Random(System.currentTimeMillis());
for(int i=0; i<iterationsCount; i++)
{
mousePos=random.nextInt(5);
for(int j=0;;j++)
{
catPos=Integer.parseInt(String.valueOf(chain.charAt(j%chain.length())));
steps++;
if(catPos==mousePos) break;
if(mousePos==0) mousePos=1;
else if(mousePos==4) mousePos=3;
else mousePos+=random.nextInt(2)*2-1;
}
}
return (double)steps/iterationsCount;
}
たとえば、computePerformanceForChain("1133")
約 3 を返します。
ただし、チェーン"23"
関数ループの場合。
なぜこうなった?ありがとう。