A solution for Project One
Below is the listing for a possible solution to the project.
/* MCS 275 Project One: random walks */
#include <stdio.h>
#include <stdlib.h>
void walk (int m, int n);
/* executes a random walk through an mxn grid,
prints the grid after each walk is completed */
int eccentricity (int m, int n, char a[m][n]);
/* returns the maximal |m-i-1-j| over all non blank entries
in the mxn grid */
void print_grid (int m, int n, char a[m][n]);
/* prints the grid of points */
void move (int m, int n, char a[m][n], int *i, int *j);
/* makes one move north or east in the mxn grid,
starting at the current tile at position (i,j) */
int coin_toss ();
/* executes a coin toss, returns 1 or 2 */
int main(void)
{
int m,n;
printf("Give number of rows : "); scanf("%d",&m);
printf("Give number of columns : "); scanf("%d",&n);
walk(m,n);
return 0;
}
void walk (int m, int n)
{
char grid[m][n];
int c,i,j,ecc;
int cnt = 0;
int maxecc = 0;
int minecc = m+n;
c = getchar();
while (c != 'q')
{
for (i = 0; i < m; ++i) /* initialize the grid */
for (j = 0; j < n; ++j)
grid[i][j] = ' ';
i = m-1; /* (i,j) marks position */
j = 0;
grid[i][j] = '+';
while ((i != 0) || (j != n-1)) /* do the walk */
move(m,n,grid,&i,&j);
print_grid(m,n,grid); /* print grid and eccentricity */
ecc = eccentricity(m,n,grid);
printf("Eccentricity of the walk : %d\n", ecc);
++cnt; /* update statistics */
if (ecc > maxecc) maxecc = ecc;
if (ecc < minecc) minecc = ecc;
printf("Type q to quit. Press enter to continue...");
c = getchar();
}
printf("Result of %d random walks in %d-by-%d grid :\n", cnt,m,n);
printf(" Minimal eccentricity of walks : %5d \n", minecc);
printf(" Maximal eccentricity of walks : %5d \n", maxecc);
}
void print_grid (int m, int n, char a[m][n])
{
int i,j;
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
putchar(a[i][j]);
printf("\n");
}
}
int eccentricity (int m, int n, char a[m][n])
{
int i,j,ecc = 0;
for (i = 0; i < m; ++i)
for (j = 0; j < n; ++j)
if (a[i][j] == '+')
if (abs(m-i-j-1) > ecc)
ecc = abs(m-i-j-1);
return ecc;
}
int coin_toss ()
{
int r = rand();
if (r < RAND_MAX/2)
return 1;
else
return 2;
}
void move (int m, int n, char a[m][n], int *i, int *j)
{
int r = coin_toss();
if ((r == 1) && (*i > 0))
a[--*i][*j] = '+';
else
if (*j < n-1)
a[*i][++*j] = '+';
}