Game:
There is a box divided into five sections. Inside the box sits mouse. Cat sitting near the box.
Each turn, cat puts his paw on the section.
1) if the cat put his paw on the section with the mouse, the game is over
2) else, otherwise, the mouse moves to the neighboring section, including the section under the cat's paw
I'm trying to find a strategy cat which will win in a minimum number of moves (in average).
Chain - cyclically repeating sequence of moves of the cat.
The following function returns the average number of moves to win for a given chain:
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;
}
For example, computePerformanceForChain("1133") returns approximately 3.
But for chain "23" function loops.
Why is this happening? Thanks.
0to start with, then it could end up unluckily bouncing between0and1. There is no guarantee that you will land on2or3whencatPosdoes, ever.