I have a 2 dimensional array filled with 0s and 1s. I have to display that array in way that:
– 0s are always shown
– 1s are shown one at the time.
It suppose to look like a maze where 0 is a wall and 1 is a current position.
How can I do that in c++?
EDIT:
I came up with a solution but maybe there is simpler one. What if I’d create copy of my _array and copy 0s and blank spaces instead of 1s to it. Then in loop I’d assign one of _array “1” to second array then display whole array and then make swap 1 back with blank space?
EDIT2:
int _tmain(int argc, _TCHAR* argv[])
{
file();
int k=0,l=0;
for(int i=0;i<num_rows;i++)
{
for(int j=0;j<num_chars;j++)
{
if(_array[i][j] == 1)
{
k=i;
l=j;
break;
}
}
}
while(1)
{
for(int i=0;i<num_rows;i++)
{
for(int j=0;j<num_chars;j++)
{
if(_array[i][j] == 0) printf("%d",_array[i][j]);
else if(_array[i][j]==1)
{
if(k==i && l==j)
{
printf("1");
}
else printf(" ");
}
l++;
if(l>num_chars) break;
}
k++;
l=0;
printf("\n");
}
k=0;
system("cls");
}
return 0;
}
I wrote something like that but still i don’t know how to clear screen in right moment. Function file() reads from file to 2D array.
Assuming you want something like that
You could print a
0whenever it occurs and a blank space if not. To handle the current position you could use two additional variables likeposX,posY. Now everytime you find a1in your array you checkif (j == posX && i = posY)and print1if so…As you just need to visualize the maze at different possible positions I’d propose a simple display function.
DisplayMaze(int x, int y)is printing the maze in the required format to the screen. If_array[y][x] == 1there is also printed a single1…In order to display all possible positions you have to iterate over all of them and check if the current position is marked with
1in the array (otherwise displaying would’t make sense)The output should look like:
…
However, i’d recommend a more C++ like approach as a maze could be implemented as a class. This class could bring it’s own display-method and would encapsulate the internal data. It could basically look like:
it would be used as followes: