简体   繁体   中英

Printing a 2d array using a 1d array

I am working on an eight queens/ chess board problem in my class. For my code, i am using a one dimensional array ie q[c](c is the column) to store the value of the row which consists of a queen. for example, q[1]=3 means that in column 2 (0 based array), there is a queen in row 4.

The original problem used a 2d array, so b[r][c] would either = 0, or 1, 1 being a queen, 0 being the rest. The program used an ok function to test each queen it was placing against all previously placed queens, and at the end, printed the result.

The print function was
for(int j=0; j<c;j++)
   cout<<endl;
   for(int i=0; i<c;i++)
      cout<< b[i][j];

which printed 92 solution boards that looked something like this

10000000
00001000
01000000
00010000
00000010
00100000
00000100
00000001

Now for my issue: I can NOT for the life of me figure out how to get the aforementioned 1d array b[c] to print a board which looks the same as this. I am a beginner comp sci student but i still thought this would be much more trivial.

I am not looking for an answer, more of a hint to lead me in the right direction, or maybe the first line of code. Help is MUCH appreciated. thanks

Something like....

for (int y = 0; y<8; y++) {
   int val = b[y];
   for (int x=0; x<8; x++) {
      x==val ? printf("1") : printf("0") ;
   }
   printf("\n");
}

or

    for (int y = 0; y<8; y++) {
       char[9] line;
       strcpy(line,"00000000");
       line[b[y]] = '1';
       printf("%s\n",line);
    }

I guess that if your array would tell you in which column of each row a queen is, you'd figure out the solution easily. Unfortunately, you have to produce your output row-by-row since that is how text terminals like it. It's not that hard either:

  • For each row:
    • For each column:
      • If there is a queen at (row, column): print 1, else print 0

You already have the code for this. Except for the “if there is a queen…” part. So let's break the problem up and make it a function:

bool is_there_a_queen(const int[8] board, int row, int col);

Will you be able to implement is_there_a_queen ?

#include <iostream>

/*
10000000
00001000
01000000
00010000
00000010
00100000
00000100
00000001
*/

int main()
{
   int q[] = {0, 4, 1, 3, 6, 2, 5, 7};
   for (int i = 0; i < 8; ++i )
   {
      for (int j = 0; j < 8; ++j )
      {
         if ( q[i] == j )
         {
            std::cout << 1;
         }
         else
         {
            std::cout << 0;
         }
      }
      std::cout << std::endl;
   }
   return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM