Eight Queens Arrays

I've had a question about these type of arrays before and was able to get it but now it is asking something I can't seem to get. This is the question at stake: Eight queens are to be placed on an 8x8 chessboard in such a way that one queen is to be in each row and column. Your program will prompt the user to enter, for each column, the row that contains a queen. Determine if the given configuration has exactly one queen in each row and one in each column; print "Yes" if so, "No" otherwise.

Use an array board[8] to represent a board configuration. If board[c] has value r, then in row r there is a queen in column c.

It's supposed to end up asking if they align with a yes or no. I've got the code to the point where it aligns them but I don't know how to determine if the pattern entered will align. This is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

int main()
{
  cout << "Enter the rows containing queens, in order by column: ";
//Collects the data for the array.
  int board[8];
  for(int i = 0; i < 8; i++)
    cin >> board[i];
//Prints the board.
  for(int i = 0; i < 8; i++)
  {
    for(int j = 0; j < 8; ++j)
    {
        if(i == board[j])
            cout<<'Q';
        else
            cout<<'.';
    }
    cout<< endl;
  }
}
To check, what I would do is create a one dimensional array initialize it to 0 and as you cycle through the rows of the user defined array check for a queen in each slot if there is a queen in board[j] increment the number [j] in the check array, after that is complete you then cycle through the check array insuring each number is one if not, it doesn't meet the requirement.

If this does not make sense to you, repost and ill provide further clarification.

and note

1
2
3
4
 
int board[8]; //< -- 1 dimension array

// shouldn't you be using a 2 dimensional array? 


EDIT: ok I misunderstood, you actually have to use a 1 dimensional array.
Let me ponder that.
Last edited on
ok this is how I would do it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

        int q = 0;

	// checking loop
	for (int i = 0; i < 8; i++)
	{
		q = 0; // variable equals 0 at the start of each cycle

		for (int j = 0; j < 8; i++)
		{
			// if the array has a value i then
			// there is indeed a queen in that row
			// if there is more than one queen increment again
			if (board [j] == i)
			{
				q++; 
			}
		}

		// if there is not one queen in each row
		// condition fails print false and finish program
		if (q != 1)
		{
			cout << "No";
			return 0;
		}
	}

	// program was not finished earlier so print true
	cout << "Yes";


I haven't tested it but it should work.

If you accept answer please mark thread as solved as it helps us help you :P
Last edited on
Topic archived. No new replies allowed.