# Thread: stochastic process for a chess problem

1. ## Re: stochastic process for a chess problem

I am not proficient in R, so here is my outline:

Function countmoves
Have a vector $v$ that stores two integers. Initialize it to $(1,1)$.
Start a counter at zero.
Start loop
Pick a random number $a$ (1 or 2). Then pick a random number $b$ (1 through 8). If $v[a]=b$ pick a new $a,b$ (restart loop). Otherwise, increase counter by one and set $v[a]=b$. If $v[1]=v[2]=8$ return counter.
End loop
End function
Now, run this function say 500 times and take the average.

2. ## Re: stochastic process for a chess problem

The problem is the rook can only move either horizontally or vertically , how can I put that condition into account? Thanks

從我的iPhone使用Tapatalk 發送

3. ## Re: stochastic process for a chess problem

Originally Posted by pupupanda
The problem is the rook can only move either horizontally or vertically , how can I put that condition into account? Thanks

從我的iPhone使用Tapatalk 發送
That is already accounted for. So long as you only modify one variable at a time, the rook is only moving horizontally or vertically, never both.

4. ## Re: stochastic process for a chess problem

This worked (but may not be an efficient solution):

CountMoves <- function() {
position <- c(1,1);
counter <- 0;
repeat{
newpos <- c(0,0);
newpos[1] <- sample(1:2,1);
newpos[2] <- sample(1:8,1);
if(position[newpos[1]]==newpos[2])
next;

counter <- counter+1;
position[newpos[1]] <- newpos[2];
if(position[1]==8 & position[2]==8)
return(counter);
}
}

SimulateMoves <- replicate(500,CountMoves());
mean(SimulateMoves);

----------------------
Note that position[1] can be thought of as the horizontal position and position[2] can be thought of as the vertical position. Every time it goes through the loop, it chooses a random direction (1 or 2) to update. It then chooses a random position in that rank or file (1 through 8). If it is already at that position, it begins the loop again (it did not move, so the counter should not update, it should just try again to move). If the randomly chosen new position is different from its current position (again, it is only changing one direction at a time), then it increments the counter and updates the rook's position. Then it checks, is the rook at the end square (8,8)? If it is, it returns the value of the counter and exits the function. Otherwise, it keeps looping until it does reach (8,8).

Page 2 of 2 First 12