Program to find number of expected moves required to win Lotus and Caterpillar game in Python

PythonServer Side ProgrammingProgramming

Suppose we have a grid with n rows and m columns. Amal and Bimal are playing a game on that grid. The game rule is like below −

Amal places white lotus tile somewhere at the top row and Bimal places a caterpillar tile somewhere on the bottom row. Amal starts the game and they are playing alternatively. Amal can move his tile to any of the 8 adjacent cells inside the grid of the current cell, but Bimal's caterpillar tile can only move left or right inside the grid, or stay at the same position. Amal's goal is to catch Bimal using as few moves as possible, while Bimal (with the caterpillar tile) has to survive for as long as possible. If they randomly select two columns to put their lotus and caterpillar, then we have to find expected number of moves required to win this game by Amal.

So, if the input is like n = 5 m = 7, then the output will be 4.571428571428571.

To solve this, we will follow these steps −

  • r := 0
  • for l in range 0 to m - 1, do
    • temp := n - 1.0
    • if l >= n, then
      • temp := temp + (l - n + 1) * ((l - 1) / m)
    • if l < m - n, then
      • temp := temp + (m - n - l) * ((m - l - 2) / m)
    • r := r + temp / m
  • return r

Example

Let us see the following implementation to get better understanding −

def solve(n, m):
   r = 0

   for l in range(m):
      temp = n - 1.0
      if l >= n:
         temp += (l - n + 1) * ((l - 1) / m)
      if l < m - n:
         temp += (m - n - l) * ((m - l - 2) / m)
      r += temp / m

   return r

n = 5
m = 7
print(solve(n, m))

Input

5, 7

Output

4.571428571428571
raja
Published on 25-Oct-2021 07:36:43

Advertisements