Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find number of expected moves required to win Lotus and Caterpillar game in Python
Suppose we have a grid with n rows and m columns. Amal and Bimal are playing a strategic game on this grid with specific movement rules.
Game Rules
The game follows these rules:
- Amal places a white lotus tile somewhere in the top row
- Bimal places a caterpillar tile somewhere in the bottom row
- Amal starts first, and they play alternately
- Amal can move to any of the 8 adjacent cells (including diagonals)
- Bimal's caterpillar can only move left, right, or stay in the same position
- Amal's goal is to catch Bimal using minimum moves
- Bimal's goal is to survive as long as possible
Problem Statement
If both players randomly select columns for their initial positions, we need to find the expected number of moves required for Amal to win the game.
Algorithm
The solution follows these steps:
- Initialize result
r = 0 - For each possible lotus position
lfrom 0 to m-1: - Calculate base moves:
temp = n - 1.0(vertical distance) - If lotus is far right (
l >= n): add extra moves for horizontal chase - If lotus is far left (
l ): add extra moves for horizontal chase - Add weighted contribution to result
- Return the expected value
Example
Let's solve this with a grid of 5 rows and 7 columns:
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
# Test with grid dimensions
n = 5 # rows
m = 7 # columns
result = solve(n, m)
print(f"Expected moves required: {result}")
Expected moves required: 4.571428571428571
How It Works
The algorithm calculates the expected value by considering all possible starting positions:
-
Base case:
n - 1moves needed to traverse vertically - Right edge penalty: When lotus starts far right, caterpillar can escape leftward
- Left edge penalty: When lotus starts far left, caterpillar can escape rightward
-
Weighted average: Each scenario is weighted by
1/mprobability
Conclusion
This solution efficiently calculates the expected number of moves by analyzing optimal strategies for both players. The formula accounts for geometric constraints and probabilistic positioning in the Lotus and Caterpillar game.
