I am trying to produce a random walk solution but I get some strange results.
The program must randomly "walk" from element to element, always going up, down, left or right by one element.
The elements visited by the program will be labeled with the letters A through Z, in the order visited.
If all four directions are blocked, the program must terminate.
Here's the code :
Code:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
int main (int argc, const char * argv[]) {
// insert code here...
char myArray[10][10];
char letters[26] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
int counter1 = 0; //row
int counter2 = 0; //column
int direction; //variable to hold the direction of the next move
int counter = 0;
srand( (unsigned)time(NULL) );
//fill myArray with dots
for (int theCounter = 0; theCounter < 10; theCounter++)
{
for (int innerCounter = 0; innerCounter < 10; innerCounter++) {
myArray[theCounter][innerCounter] = '.';
}
}
myArray[0][0] = letters[counter];
while (counter < 26) {
//decide direction
direction = rand() % 4; //picks a random direction (0 - up, 1 - down, 2 - left, 3 - right)
//up case
if (direction == 0) //bounders
{
if (counter1 == 0) {
continue;
}
else if (myArray[counter1 - 1][counter2] == '.')
{
counter++;
counter1--;
myArray[counter1][counter2] == letters[counter];
}//end if
}//outer if
//down case
if (direction == 1) //bounders
{
if (counter1 > 9)
{
continue;
}
else {
counter++;
counter1++;
myArray[counter1][counter2] = letters[counter];
}//end if
}//end outer if
//left case
if (direction == 2)
{
if (counter2 == 0)
{
continue;
}
else if (myArray[counter1][counter2 - 1] == '.')
{
counter++;
counter2--;
myArray[counter1][counter2] == letters[counter];
}//end if
}//end outer if
//right case
if (direction == 3) //bounders
{
if (counter1 > 8)
{
continue;
}
else if (myArray[counter1][counter2 + 1] == '.')
{
counter++;
counter2++;
myArray[counter1][counter2] == letters[counter];
}//end inner if
}//end outer if
}//end while
//print the grid
for (int theCounter = 0; theCounter < 10; theCounter++)
{
for (int innerCounter = 0; innerCounter < 10; innerCounter++) {
printf("%c", myArray[theCounter][innerCounter]);
}
printf("\n");
}
}
One strange thing that I found duting debugging is that when direction = 3 the command after the counter2++ expression that assigns a value to an 2 dimensional array is never executed.
Why is this happening?
Thank you.