Thanks, Salem. The srand(time(NULL)); line really worked, of course after I included <time.h> header.
As for the long if statements, yes, that was stupid. I've added the rows as i and the columns as j. As for the other two long if statements (4 conditions each), I can't seem to find a better way to do them than the pointer I'm using for them. Everything is working perfectly except that it is still going off the edge to the left or right, but not up or down - i.e. the row condition seems to be working but the column edge condition doesn't seem to be. I can't figure out what the problem is.
Also, while the cursor that is pointing to the beginning of the matrix should be filling the first element of the array when I run the statement *cursor = elem; but instead it is actually starting at the second so I had to do cursor-- before executing the Matrix Random Walk logic.
Btw, I'm using the MinGW GCC 6.1.0 compiler on a Windows 10, 64-bit computer, with Dev-C++ as my editor.
Below is the code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
// main declarations
char matrix[10][10], *cursor;
int direction;
unsigned char elem = 'A';
// fill the matrix elements with .
for (cursor = &matrix[0][0]; cursor <= &matrix[9][9]; cursor++)
{
*cursor = '.';
}
/* walk randomly through the matrix, printing the alphabet in order as we go */
// first some declarations and initializations for our main cursor pointer and the row and column indicators
cursor = &matrix[0][0];
cursor--;
int i = 0, j = 0;
// for rand()
srand(time(NULL));
// now for the main logic, the Matrix Random Walk
while (elem < 91)
{
direction = rand() % 4;
switch (direction)
{
Up:
case 0:
if ((*(cursor+1) != '.') && (*(cursor-1) != '.') && (*(cursor+10) != '.') && (*(cursor-10) != '.'))
goto printMatrix;
if (i > 0)
{
cursor -= 10;
i--;
}
else goto Right;
if (*cursor == '.')
*cursor = elem;
else
{
cursor += 10;
i++;
goto Right;
}
break;
Right:
case 1:
if ((*(cursor+1) != '.') && (*(cursor-1) != '.') && (*(cursor+10) != '.') && (*(cursor-10) != '.'))
goto printMatrix;
if (j < 9)
{
cursor++;
j++;
}
else goto Left;
if (*cursor == '.')
*cursor = elem;
else
{
cursor--;
j--;
goto Left;
}
break;
Left:
case 2:
if ((*(cursor+1) != '.') && (*(cursor-1) != '.') && (*(cursor+10) != '.') && (*(cursor-10) != '.'))
goto printMatrix;
if (j > 0)
{
cursor--;
j--;
}
else goto Down;
if (*cursor == '.')
*cursor = elem;
else
{
cursor++;
j++;
goto Down;
}
break;
Down:
case 3:
if ((*(cursor+1) != '.') && (*(cursor-1) != '.') && (*(cursor+10) != '.') && (*(cursor-10) != '.'))
goto printMatrix;
if (i < 9)
{
cursor += 10;
i++;
}
else goto Up;
if (*cursor == '.')
*cursor = elem;
else
{
cursor -= 10;
i--;
goto Up;
}
break;
}
elem++;
}
// print the matrix
printMatrix:
for (int i = 0, j = 0; i < 10; i++)
{
for (j = 0; j < 10; j++)
{
printf("%c ", matrix[i][j]);
}
printf("\n");
}
// end main
return 0;
}