AY 23-24 Ass 2
AY 23-24 Ass 2
AY 23-24 Ass 2
Problem statement:
Random walk: A (drunken) cockroach is placed on a given square in the middle of a tile floor
in a rectangular room of size n x m tiles. The bug wanders (possibly in search of an aspirin)
randomly from tile to tile throughout the room. Assuming that it may move from his present
tile to any of the eight tiles surrounding it (unless it is against a wall) with equal probability,
how long will it take him to touch every tile on the floor at least once?
Write a C++ program to graphically show a random walk of a (drunken) cockroach and find
the no of moves made.
Objectives:
Understand the use of array.
Understand random walk problems.
Theory:
Random Walk Problems:
Random walk concept is often used to simulate the movement of the particles or creatures in
physics and computer science.
That is, if (i, j) is the initial position of the cockroach then the cockroach can only move on
the tiles as shown in the following figure-
Figure 1
So there are 8 possible cases for the cockroach to move.
For that we will keep on generating a random number from 1 to 8 and based on the number
generated we can implement these above cases (using switch case) and make the cockroach
move the tile.
srand(time(0))
int lb=20,ub=45; //including 20 and 45
for (int i=0;i<25;i++)
{
cout<<(rand()%(ub-lb+1)+lb)<<endl;
}
To check whether matrix is filled or not there are many ways. Choose suitable logic
according to your preference.
For example one of the logic could be:
Above logic is easy to understand but increases the time complexity of our program.
Algorithm:
Step 1: Start
Step 5: while(matrix_is_filled)
Generate random number and check whether it is valid move or not.
If valid :
Totalmoves++
Else :
Again generate number
Step 7: Stop
Time complexity: Discuss the time complexity of following function with respect to best
case and worst case
Practice problem:
Write possible cases for a knight to move on the chess board.(See figure 1)