我在2d中模拟随机游走,周期性边界。我的代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/**
*creates the environment in the form of a matrix of ones and zeros, random walk
*/
#define ROWS 3
#define COLS 3
#define MOVES 1
#define DIRECTIONS 4
int main(void)
{
srand(time(NULL)); //seed for the random number generator
int array[ROWS][COLS]; //array for the environment
int x, y; //row and column for loop purposes
int min = 0; //min number in the array
int max = 1; // max number in the array
for(x = 0; x < ROWS; x++) //loop to fill array
{
for(y = 0; y < COLS; y++)
{
array[x][y] = min + rand() % (max - min + 1);
printf("%d", array[x][y]);
}
printf("\n");
}
int steps = 0; //step counter
int direction; //direction will be chosen at random
int i = rand() % ROWS; //Assign start position row
int j = rand() % COLS; //Assign start position column
printf("initial position: %d %d \n", i, j);
while (steps < MOVES)
{
direction = rand() % DIRECTIONS; // 0 = N, 1 = S, 2 = E, 3 = W
printf("direction: %d \n", direction);
switch (direction)
{
case 0: // north
i = ((i - 1) % ROWS);
break;
case 1: // south
i = ((i + 1) % ROWS);
break;
case 2: // east
j = ((j + 1) % COLS);
break;
case 3: // west
j = ((j - 1) % COLS);
break;
}
printf("new position: %d %d \n", i, j);
steps++; //update step counter
printf("number of steps: %d \n", steps);
}
return 0;
}
当我获得方向S或E时,边界条件正常。初始位置1 2的E的结果是新位置1 0.但是如果我得到位置N或W,则边界条件不起作用。初始位置为0 1的N的结果是新位置-1 1,应该是2 1.如何修复我的代码?谢谢。