Question

I have a question about C++. I have to code the 8 queens puzzle without using...

I have a question about C++. I have to code the 8 queens puzzle without using any recursive methods. Every time the program runs, it will randomly place 8 queens throughout the board. I got that working, but the issue is the board is suppose to be filled with asterisks and the queens are suppose to be represented with a Q. I have put zeros instead of asterisks and ones instead of Qs, i tried to fix it but it wont work for some reason, thats the only issue with my program, down below i have to code to it, may someone please take a look at it and try to fix my problem and copy the code in here please! Thank you!

// Eight Queens

// 1-2-2020

// Period 5

#include <iostream>

#include <time.h>

#include <stdlib.h>

using namespace std;

bool canPlaceRC(int, int);

bool canPlaceDiag(int, int);

void fillQueens();

void resetBoard();

void printBoard();

//Constant variable to replace all '8'

const int SIZE = 8;

int board[SIZE][SIZE];

int main()

{

srand(time(0));

resetBoard();

fillQueens();

return 0;

}

bool canPlaceDiag(int c1, int c2)

{

//Creates new variables to match coordinates

int x = c1;

int y = c2;

//Going to top left

while (x >= 0 && y >= 0)

{

x--;

y--;

if (board[x][y] == 1)

{

return false;

}

else

{

continue;

}

}


//Resets x and y to match original coordinates

x = c1;

y = c2;

//Going to bottom right

while (x < SIZE && y < SIZE)

{

x++;

y++;

if (board[x][y] == 1)

{

return false;

}

else

{

continue;

}

}

x = c1;

y = c2;

//Going to top right

while (x >= 0 && y < SIZE)

{

x--;

y++;

if (board[x][y] == 1)

{

return false;

}

else

{

continue;

}

}

x = c1;

y = c2;

//Going to bottom left

while (x < SIZE && y >= 0)

{

x++;

y--;

if (board[x][y] == 1)

{

return false;

}

else

{

continue;

}

}

//If all have not returned False, return True;

return true;

}

bool canPlaceRC(int c1, int c2)

{

//Variables to check if a queen is in the same row or column

int sum1 = 0;

int sum2 = 0;

bool checkC;

bool checkR;


//Checker for columns

for (int x = 0; x < SIZE; x++)

{

//Sum1 is adding all numbers in a vertical iteration starting from zero

sum1 += board[x][c2];

}

//If the sum is 0, then there were no Queens in its' column

if (sum1 == 0)

{

checkC = true;

}

else

{

checkC = false;

}

//Checker for rows

for (int x = 0; x < SIZE; x++)

{

//Sum2 is adding all numbers in a horizontal iteration starting from zero

sum2 += board[c1][x];

}

if (sum2 == 0)

{

checkR = true;

}

else

{

checkR = false;

}

//Checks if both returned true

if ((checkR == true) && (checkC == true))

{

return true;

}

else

{

return false;

}

}

void resetBoard()

{

//Goes through every spot in board, setting it all to zero

for (int r = 0; r < SIZE; r++)

{

for (int c = 0; c < SIZE; c++)

{

board[r][c] = 0;

}

}

}

void printBoard()

{

//Space to seperate headers

cout << " ";

//Prints the header

for (int i = 0; i < SIZE; i++)

{

cout << i << " ";

}

cout << endl;

//Prints the side header while also printing the rows for the matrix

for (int y = 0; y < SIZE; y++)

{

cout << y << " ";

for (int x = 0; x < SIZE; x++)

{

//Goes through the matrix horizontally

cout << board[x][y] << " ";

}

cout << endl;

}

}

void fillQueens()

{

//Counter so that only 8 queens are placed

int count = 0;

//Counter to check how many times the queen placement has not worked

int notWork = 0;

while (count < SIZE)

{

//Generates a random coordinate for a queen

int c1 = rand() % SIZE;

int c2 = rand() % SIZE;

//If both horizontal, vertical and diagonal checks are true, place the queen

if (canPlaceRC(c1, c2) == true && canPlaceDiag(c1, c2) == true)

{

board[c1][c2] = 1;

// USED FOR DEBUGGING: cout << "Queen at: " << c1 << ", " << c2 << endl;

count++;

}

else

{

notWork++;

//64 because there are 64 slots in the board. Even though some may be repeated, this just ensures most, if not all, spots

if (notWork == 64)

{

// USED FOR DEBUGGING: cout << "RESET" << endl;

//Resets the board to all 0's, resets the failure counts and number of times a queen can be placed

resetBoard();

notWork = 0;

count = 0;

}

//If the fail count is not 64, generate a new random coordinate

continue;

}

}

printBoard();

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Please find the solution below. I have made a small and efficient change to do the needful as mentioned in the question above. I have also highlighted (bold) the modified code and added comments for it.

C++ Source Code

// Eight Queens

// 1-2-2020

// Period 5

#include <iostream>

#include <time.h>

#include <stdlib.h>

using namespace std;

bool canPlaceRC(int, int);

bool canPlaceDiag(int, int);

void fillQueens();

void resetBoard();

void printBoard();

//Constant variable to replace all '8'

const int SIZE = 8;

int board[SIZE][SIZE];

int main()

{

srand(time(0));

resetBoard();

fillQueens();

return 0;

}

bool canPlaceDiag(int c1, int c2)

{

//Creates new variables to match coordinates

int x = c1;

int y = c2;

//Going to top left

while (x >= 0 && y >= 0)

{

x--;

y--;

if (board[x][y] == 1)

{

return false;

}

else

{

continue;

}

}

//Resets x and y to match original coordinates

x = c1;

y = c2;

//Going to bottom right

while (x < SIZE && y < SIZE)

{

x++;

y++;

if (board[x][y] == 1)

{

return false;

}

else

{

continue;

}

}

x = c1;

y = c2;

//Going to top right

while (x >= 0 && y < SIZE)

{

x--;

y++;

if (board[x][y] == 1)

{

return false;

}

else

{

continue;

}

}

x = c1;

y = c2;

//Going to bottom left

while (x < SIZE && y >= 0)

{

x++;

y--;

if (board[x][y] == 1)

{

return false;

}

else

{

continue;

}

}

//If all have not returned False, return True;

return true;

}

bool canPlaceRC(int c1, int c2)

{

//Variables to check if a queen is in the same row or column

int sum1 = 0;

int sum2 = 0;

bool checkC;

bool checkR;

//Checker for columns

for (int x = 0; x < SIZE; x++)

{

//Sum1 is adding all numbers in a vertical iteration starting from zero

sum1 += board[x][c2];

}

//If the sum is 0, then there were no Queens in its' column

if (sum1 == 0)

{

checkC = true;

}

else

{

checkC = false;

}

//Checker for rows

for (int x = 0; x < SIZE; x++)

{

//Sum2 is adding all numbers in a horizontal iteration starting from zero

sum2 += board[c1][x];

}

if (sum2 == 0)

{

checkR = true;

}

else

{

checkR = false;

}

//Checks if both returned true

if ((checkR == true) && (checkC == true))

{

return true;

}

else

{

return false;

}

}

void resetBoard()

{

//Goes through every spot in board, setting it all to zero

for (int r = 0; r < SIZE; r++)

{

for (int c = 0; c < SIZE; c++)

{

board[r][c] = 0;

}

}

}

void printBoard()

{

//Space to seperate headers

cout << " ";

//Prints the header

for (int i = 0; i < SIZE; i++)

{

cout << i << " ";

}

cout << endl;

//Prints the side header while also printing the rows for the matrix

for (int y = 0; y < SIZE; y++)

{

cout << y << " ";

for (int x = 0; x < SIZE; x++)

{

//Goes through the matrix horizontally
// if board[x][y]==0 (not queen) print "*"
if(board[x][y] == 0)
cout<<"*" << " ";
// else if board[x][y]==1 (queen) print "Q"
else
cout << "Q" << " ";

}

cout << endl;

}

}

void fillQueens()

{

//Counter so that only 8 queens are placed

int count = 0;

//Counter to check how many times the queen placement has not worked

int notWork = 0;

while (count < SIZE)

{

//Generates a random coordinate for a queen

int c1 = rand() % SIZE;

int c2 = rand() % SIZE;

//If both horizontal, vertical and diagonal checks are true, place the queen

if (canPlaceRC(c1, c2) == true && canPlaceDiag(c1, c2) == true)

{

board[c1][c2] = 1;

// USED FOR DEBUGGING: cout << "Queen at: " << c1 << ", " << c2 << endl;

count++;

}

else

{

notWork++;

//64 because there are 64 slots in the board. Even though some may be repeated, this just ensures most, if not all, spots

if (notWork == 64)

{

// USED FOR DEBUGGING: cout << "RESET" << endl;

//Resets the board to all 0's, resets the failure counts and number of times a queen can be placed

resetBoard();

notWork = 0;

count = 0;

}

//If the fail count is not 64, generate a new random coordinate

continue;

}

}

printBoard();

}

Output

Add a comment
Know the answer?
Add Answer to:
I have a question about C++. I have to code the 8 queens puzzle without using...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Please help i need a C++ version of this code and keep getting java versions. Please...

    Please help i need a C++ version of this code and keep getting java versions. Please C++ only Purpose: This lab will give you experience harnessing an existing backtracking algorithm for the eight queens problem, and seeing its results displayed on your console window (that is, the location of standard output). Lab A mostly complete version of the eight queens problem has been provided for you to download. This version has the class Queens nearly completed. You are to provide...

  • There is a problem with thecode. I get the error messages " 'board' was not declared...

    There is a problem with thecode. I get the error messages " 'board' was not declared in this scope", \src\TicTacToe.cpp|7|error: expected unqualified-id before ')' token| \src\TicTacToe.cpp|100|error: expected declaration before '}' token| Here is the code #ifndef TICTACTOE_H #define TICTACTOE_H #include class TicTacToe { private: char board [3][3]; public: TicTacToe () {} void printBoard(); void computerTurn(char ch); bool playerTurn (char ch); char winVerify(); }; ************************************ TicTacToe.cpp #endif // TICTACTOE_H #include "TicTacToe.h" #include #include using namespace std; TicTacToe() { for(int i =...

  • ================Data Structures C++=============== – Implement the Eight Queens Problem This is a...

    ================Data Structures C++=============== – Implement the Eight Queens Problem This is an object oriented program. This is #1 on page 187 of your book with ONE difference, I’m requiring you add a client program to test your code (a main). If you have the old book the question says “Complete the Queen and Board class for the Eight Queens problem.” On page 179 of your book is a function placeQueens that solves the Eight Queens problem. On page 180 of...

  • Can you explain how this code for the 8 Queens Problem works? It's in C++ In case you dont know w...

    Can you explain how this code for the 8 Queens Problem works? It's in C++ In case you dont know what the 8 Queens problem is, "The eight queens puzzle is the problem of placing eightchess queens on an 8×8 chessboard so that no two queensthreaten each other; thus, a solution requires that no two queens share the same row, column, or diagonal." This is the code: #include <iostream> #include <cmath> using namespace std; bool ok(int q[], int c) {     ...

  • how to randomly generate moves until the whole board is filled?. If the board size is...

    how to randomly generate moves until the whole board is filled?. If the board size is c*r, you can only call the random function rand() c*r times (excluding the random function rand() that have been used in the provided code). Below is the code I need to convert. It is manual right now (user inputs numbers until whole board filled). I also have a piece of algorithmn below..but am unsure of how I can use it in the code: //Algorithm...

  • I just need a help in replacing player 2 and to make it unbeatable here is my code: #include<i...

    I just need a help in replacing player 2 and to make it unbeatable here is my code: #include<iostream> using namespace std; const int ROWS=3; const int COLS=3; void fillBoard(char [][3]); void showBoard(char [][3]); void getChoice(char [][3],bool); bool gameOver(char [][3]); int main() { char board[ROWS][COLS]; bool playerToggle=false; fillBoard(board); showBoard(board); while(!gameOver(board)) { getChoice(board,playerToggle); showBoard(board); playerToggle=!playerToggle; } return 1; } void fillBoard(char board[][3]) { for(int i=0;i<ROWS;i++) for(int j=0;j<COLS;j++) board[i][j]='*'; } void showBoard(char board[][3]) { cout<<" 1 2 3"<<endl; for(int i=0;i<ROWS;i++) { cout<<(i+1)<<"...

  • I need help of how to include the merge sort code into this counter code found...

    I need help of how to include the merge sort code into this counter code found below: #include<iostream> using namespace std; int bubble_counter=0,selection_counter=0; // variables global void bubble_sort(int [], int); void show_array(int [],int); void selectionsort(int [], int ); int main() { int a[7]={4,1,7,2,9,0,3}; show_array(a,7); //bubble_sort(a,7); selectionsort(a,7); show_array(a,7); cout<<"Bubble counter = "<<bubble_counter<<endl; cout<<"Selection Counter = "<<selection_counter<<endl; return 0; } void show_array(int array[],int size) { for( int i=0 ; i<size; i++) { cout<<array[i]<< " "; } cout<<endl; } void bubble_sort( int array[],...

  • In the C++ programming language write a program capable of playing 3D Tic-Tac-Toe against the user....

    In the C++ programming language write a program capable of playing 3D Tic-Tac-Toe against the user. Your program should use OOP concepts in its design. Use Inheritance to create a derived class from your Lab #9 Tic-Tac-Toe class. You can use ASCII art to generate and display the 3x3x3 playing board. The program should randomly decide who goes first computer or user. Your program should know and inform the user if an illegal move was made (cell already occupied). The...

  • howthe   output   of   the   following   4   program segments (a)    const int SIZE=8;    int values[SIZE]...

    howthe   output   of   the   following   4   program segments (a)    const int SIZE=8;    int values[SIZE] = {10, 10, 14, 16, 6, 25, 5, 8};    int index;    index=0;    res = values[index];    for (int j=1; j<SIZE; j++)    {        if (values[j] > res)        {            res = values[j];            index = j;        cout << index << res << endl;        }    }    cout <<...

  • The Code is C++ // tic tac toe game #include <iostream> using namespace std; const int SIZE = 9; int check(char *); void displayBoard(char *); void initBoard(char *); int main() {    char board[...

    The Code is C++ // tic tac toe game #include <iostream> using namespace std; const int SIZE = 9; int check(char *); void displayBoard(char *); void initBoard(char *); int main() {    char board[SIZE];    int player, choice, win, count;    char mark;    count = 0; // number of boxes marked till now    initBoard(board);       // start the game    player = 1; // default player    mark = 'X'; // default mark    do {        displayBoard(board);        cout << "Player " << player << "(" << mark...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT