Question

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 missing logic for the class Queens that will enable it to create a two-dimensional array that will represent a chess board with eight rows and eight columns. You are also to modify logic to display the chess board such that the display uses a nested loop to print the rows and columns of the chessboard. To do this, you must write logic for:

+clearBoard()

and modify logic for:

+displayBoard()

After this is done, you are to write a driver program named Lab4 that has a main() function responsible for making an object from the Queens class. The main() function must also use that Queens object to start the first queen of the chess board in the first column of the chess board. Once the first queen has been placed on the chess board, you must use its displayBoard() method to show you the solution to the eight queens problem

(Actually, the eight queens problem has many solutions, but the solution you will be displaying is based on the queen being placed in a specific position the first column of the chess board based on logic already programmed into the Queens class).

You are to submit for this lab:

(1) The modified Queens class with clearBoard() and displayBoard() properly working

(2) The new program driver class that has the main() method fully implemented as described previously.

The Queens class is available in these files for you to download:

Queens.hPreview the document

/* File: Queens.h */

#ifndef QUEENS_H

#define QUEENS_H

#include <iostream>

using std::cout;

/** @class Queens

* The Queen class. */

class Queens

{

private:

// chess board -- a C++ 2-dimensional dynamic array

int **board;

// squares per row or per column

const static int BOARD_SIZE = 8;

//used to indicate empty square

const static int EMPTY = 0;

//used to indicate square contains a queen

const static int QUEEN = 1;

public:

Queens();

// --------------------------------------------------

// Constructor: Create an empty square board.

// --------------------------------------------------

void clearBoard();

// --------------------------------------------------

// Clears the board.

// Precondition: None.

// Postcondition: Sets all squares to EMPTY

// --------------------------------------------------

void displayBoard();

// --------------------------------------------------

// Displays the board.

// Precondition: None.

// Postcondition: Board is written to standartd

// output; zero is an EMPTY square, one is a square

// containing a queen (QUEEN)

// --------------------------------------------------

bool placeQueens(int column);

// --------------------------------------------------

// Place queens in columns of the board beginning

// at the column specified.

// Precondition: Queens are placed correctly in

// columns 1 thro coulumn-1.

// Postcondition: If a solution is found, each

// column of the board contains one queen and method

// returns true; otherwise retruns false (no

// solution existis for a queen anywhere in column

// specified).

// --------------------------------------------------

void setQueen(int row, int column);

// --------------------------------------------------

// Set a queen at square indicated by row and

// column.

// Precondition: None.

// Postcondition: Sets the square on the board in a

// given row and column to QUEEN.

// --------------------------------------------------

void removeQueen(int row, int column);

// --------------------------------------------------

// Remove a queen at square indicated by row and

// column.

// Precondition: None.

// Postcondition: Sets the square on the board in a

// given row and column to EMPTY.

// --------------------------------------------------

bool isUnderAttack(int row, int column);

// --------------------------------------------------

// Determines whether the square on the board at a

// given row and column is under attack by any queens

// in the columns 1 through column-1.

// Precondition: Each column between 1 and column-1

// has a queen placed in a square at a specific row.

// None of these queens can be attacked by any other

// queen.

// Postcondition: If the deignated square is under

// attack, returns true; otherwise, returns false.

// --------------------------------------------------

}; // end Queens

#endif

// Postcondition: If a solution is found, each

// column of the board contains one queen and method

// returns true; otherwise retruns false (no

// solution existis for a queen anywhere in column

// specified).

// --------------------------------------------------

void setQueen(int row, int column);

// --------------------------------------------------

// Set a queen at square indicated by row and

// column.

// Precondition: None.

// Postcondition: Sets the square on the board in a

// given row and column to QUEEN.

// --------------------------------------------------

void removeQueen(int row, int column);

// --------------------------------------------------

// Remove a queen at square indicated by row and

// column.

// Precondition: None.

// Postcondition: Sets the square on the board in a

// given row and column to EMPTY.

// --------------------------------------------------

bool isUnderAttack(int row, int column);

// --------------------------------------------------

// Determines whether the square on the board at a

// given row and column is under attack by any queens

// in the columns 1 through column-1.

// Precondition: Each column between 1 and column-1

// has a queen placed in a square at a specific row.

// None of these queens can be attacked by any other

// queen.

// Postcondition: If the deignated square is under

// attack, returns true; otherwise, returns false.

// --------------------------------------------------

}; // end Queens

#endi

Queens.cppPreview the document

/* File: Queens.cpp */

#include "Queens.h"

Queens::Queens() {

int rows = BOARD_SIZE;

int columns = BOARD_SIZE;

// memory allocated for elements of rows.

board = new int *[rows] ;

// memory allocated for elements of each column.

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

board[i] = new int[columns];

} // end constructor

void Queens::clearBoard() {

// place your logic to implement this method here

} // end clearBoard

void Queens::displayBoard() {

for (int i=0; i<BOARD_SIZE; i++) {

for (int j=0; j<BOARD_SIZE; j++) {

// place your logic to implement this method here

// that prints a single row of the chess board

// to the console window (i.e., standard output)

}

std::cout << "\n";

// this newline prints after a row

// of the chess board has been printed

}

} // end displayBoard

bool Queens::placeQueens(int column) {

if (column > BOARD_SIZE) {

return true; // base case

}

else {

bool queenPlaced = false;

int row = 1; // number of square in column

while ( !queenPlaced && (row <= BOARD_SIZE) ) {

// if square can be attacked

if (isUnderAttack(row, column)) {

++row; // consider next square in column

} // end if

else { // place queen and consider next column

setQueen(row, column);

queenPlaced = placeQueens(column+1);

// if no queen is possible in the next column,

if (!queenPlaced) {

// backtrack: remove queen placed earliers

// and try next square in column

removeQueen(row, column);

++row;

} // end if

} // end if

} // end while

return queenPlaced;

} // end if

} // end placeQueens

void Queens::setQueen(int row, int column) {

board[row-1][column-1] = QUEEN;

} // end setQueen

void Queens::removeQueen(int row, int column) {

board[row-1][column-1] = EMPTY;

} // end setQueen

bool Queens::isUnderAttack(int row, int column) {

// check column

for (int i=0; i<row-1; i++){

if (board[i][column-1]==1){

return true;

}

}

// check row

for (int i=0; i<column-1; i++) {

if (board[row-1][i] == 1){

return true;

}

}

// check lower diagnal

int lower_dir_row = row-2;

int lower_dir_column = column-2;

while (lower_dir_row>=0 && lower_dir_column>=0){

if (board[lower_dir_row][lower_dir_column]==1){

return true;

} else {

lower_dir_row = lower_dir_row -1;

lower_dir_column = lower_dir_column -1;

}

}

// check upper diagnal

int upper_dir_row = row;

int upper_dir_column = column-2;

while (upper_dir_row<BOARD_SIZE && upper_dir_column>=0){

if(board[upper_dir_row][upper_dir_column] ==1){

return true;

}else{

upper_dir_row = upper_dir_row +1;

upper_dir_column = upper_dir_column -1;

}

}

removeQueen(row, column);

++row;

} // end if

} // end if

} // end while

return queenPlaced;

} // end if

} // end placeQueens

void Queens::setQueen(int row, int column) {

board[row-1][column-1] = QUEEN;

} // end setQueen

void Queens::removeQueen(int row, int column) {

board[row-1][column-1] = EMPTY;

} // end setQueen

bool Queens::isUnderAttack(int row, int column) {

// check column

for (int i=0; i<row-1; i++){

if (board[i][column-1]==1){

return true;

}

}

// check row

for (int i=0; i<column-1; i++) {

if (board[row-1][i] == 1){

return true;

}

}

// check lower diagnal

int lower_dir_row = row-2;

int lower_dir_column = column-2;

while (lower_dir_row>=0 && lower_dir_column>=0){

if (board[lower_dir_row][lower_dir_column]==1){

return true;

} else {

lower_dir_row = lower_dir_row -1;

lower_dir_column = lower_dir_column -1;

}

}

// check upper diagnal

int upper_dir_row = row;

int upper_dir_column = column-2;

while (upper_dir_row<BOARD_SIZE && upper_dir_column>=0){

if(board[upper_dir_row][upper_dir_column] ==1){

return true;

}else{

upper_dir_row = upper_dir_row +1;

upper_dir_column = upper_dir_column -1;

}

}

return false;

} // end isUnderAttack

Once you are done getting the lab to work, pay particular attention to the logic in the placeQueens() method. There are comments indicating how backtracking is used. See how the recursive call is used in the case that a queen is determined to be placed, and how backtracking occurs in the case that a queen has been found to have to be taken back from a position where it was placed. See that backtracking is a way of using decisions to determine if a current state of logic should be allowed, or if the logic should be undone since the logic does not lead to a solution. Understanding this is the essence of understanding how backtracking algorithms are implemented.

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

Please let me know if you have any doubts or you want me to modify the answer. And if you find this answer useful then don't forget to rate my answer as thumps up. Thank you! :)

//main.cpp
#include <iostream>
#include "Queens.h"

using namespace std;

int main () {
    Queens a;
    a.setQueen(5, 1);
    a.displayBoard();

    cout << "Solution: " << endl;
    a.placeQueens(2);
    a.displayBoard();

    cout << "Cleared: " << endl;
    a.clearBoard();
    a.displayBoard();


    return 0;
}
--------------------------------------------------------------------------------------------------------------------------
//Queens.cpp
#include "Queens.h"
#include <iostream>

using namespace std;

Queens::Queens() {
    int rows = BOARD_SIZE;
    int columns = BOARD_SIZE;

    // memory allocated for elements of rows.
    board = new int *[rows] ;

    // memory allocated for elements of each column.
    for( int i = 0 ; i < rows ; i++ )
        board[i] = new int[columns];

} // end constructor

void Queens::clearBoard() {
    for (int i = 0; i < BOARD_SIZE; i++) {
        for (int j = 0; j < BOARD_SIZE; j++) {
            board[i][j] = EMPTY;
        }
    }
    // place your logic to implement this method here
} // end clearBoard

void Queens::displayBoard() {
    for (int i=0; i<BOARD_SIZE; i++) {
        for (int j=0; j<BOARD_SIZE; j++) {
            if (board[i][j] == QUEEN) {
                cout << QUEEN << " ";
            } else {
                cout << EMPTY << " ";
            }
            // cout << " 0 ";

        }
        std::cout << " ";

    }
} // end displayBoard

bool Queens::placeQueens(int column) {
    if (column > BOARD_SIZE) {
        return true; // base case
    }
    else {
        bool queenPlaced = false;
        int row = 1; // number of square in column

        while ( !queenPlaced && (row <= BOARD_SIZE) ) {
            // if square can be attacked
            if (isUnderAttack(row, column)) {
                ++row; // consider next square in column
            } // end if
            else { // place queen and consider next column
                setQueen(row, column);
                queenPlaced = placeQueens(column+1);
                // if no queen is possible in the next column,
                if (!queenPlaced) {
                    // backtrack: remove queen placed earliers
                    // and try next square in column
                    removeQueen(row, column);
                    ++row;
                } // end if
            } // end if
        } // end while
        return queenPlaced;
    } // end if
} // end placeQueens

void Queens::setQueen(int row, int column) {
    board[row-1][column-1] = QUEEN;
} // end setQueen

void Queens::removeQueen(int row, int column) {
    board[row-1][column-1] = EMPTY;
} // end setQueen

bool Queens::isUnderAttack(int row, int column) {
    // check column
    for (int i=0; i<row-1; i++){
        if (board[i][column-1]==1){
            return true;
        }
    }
    // check row
    for (int i=0; i<column-1; i++) {
        if (board[row-1][i] == 1){
            return true;
        }
    }

    // check lower diagnal
    int lower_dir_row = row-2;
    int lower_dir_column = column-2;
    while (lower_dir_row>=0 && lower_dir_column>=0){
        if (board[lower_dir_row][lower_dir_column]==1){
            return true;
        } else {
            lower_dir_row = lower_dir_row -1;
            lower_dir_column = lower_dir_column -1;
        }
    }

    // check upper diagnal
    int upper_dir_row = row;
    int upper_dir_column = column-2;
    while (upper_dir_row<BOARD_SIZE && upper_dir_column>=0){
        if(board[upper_dir_row][upper_dir_column] ==1){
            return true;
        }else{
            upper_dir_row = upper_dir_row +1;
            upper_dir_column = upper_dir_column -1;
        }
    }
    return false;

} // end isUnderAttack
--------------------------------------------------------------------------------------------------------------------------
//Queens.h
#ifndef QUEENS_H
#define QUEENS_H

#include <iostream>

using std::cout;

class Queens
{
private:
    // chess board -- a C++ 2-dimensional dynamic array
    int **board;

    // squares per row or per column
    const static int BOARD_SIZE = 8;

    //used to indicate empty square
    const static int EMPTY = 0;

    //used to indicate square contains a queen
    const static int QUEEN = 1;

public:
    Queens();

    void clearBoard();

    void displayBoard();

    bool placeQueens(int column);

    void setQueen(int row, int column);

    void removeQueen(int row, int column);

    bool isUnderAttack(int row, int column);


}; // end Queens

#endif
1-1 Queens [~/CLionProjects/Queens]-.../main.cpp .Queens main.cpp *증 *一△CMaiceLists.txt 분.mai.cpp出inens.cpp 1Queens.h Project ▼ -Queens-/CLionProjects/Queens ー #include ▼ using namespace std 츠 CMakeLists.txt main.cpp 6 int main t Queens.cpp 品Queen s.h External Libraries scratches and Consoles Queens a a.setQueen(5, 1); a.displayBoard(); 18 cout Solution: In endl; a.placeQueens (2) a.displayBoard(): 12 13 14 15 16 17 18 19 20 cout << Cleared: n << endl; a.clearBoard(); a.displayBoard(); return 21 ★ Messages: Build な 6:TODO Q: Messages -Terminal Build failed in 1 s 141 ms (2 minutes ago) ㅿCMake Q Event Log 21:2 LF 수 UTF-8: 4 spaces: Context: Queens [D] 맬

Add a comment
Know the answer?
Add Answer to:
Please help i need a C++ version of this code and keep getting java versions. Please...
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
  • in c++ Purpose: This lab will give you experience harnessing an existing backtracking algorithm for the...

    in c++ 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 missing logic for the class Queens that will enable it to create a two-dimensional array that...

  • Complete the program that solves the Eight Queens problem. The program’s output should look similar to:...

    Complete the program that solves the Eight Queens problem. The program’s output should look similar to: |1|0|0|0|0|0|0|0| |0|0|0|0|0|0|1|0| |0|0|0|0|1|0|0|0| |0|0|0|0|0|0|0|1| |0|1|0|0|0|0|0|0| |0|0|0|1|0|0|0|0| |0|0|0|0|0|1|0|0| |0|0|1|0|0|0|0|0| Use the Queens class given. In your implementation of the Queens class, complete the body of all methods marked as “To be implemented in Programming Problem 1.” Do not change any of the global variable declarations, constructor or placeQueens methods. Here is what I have so far with notes of what is needed. public class Queens...

  • Complete the program that solves the Eight Queens problem in java only please (pages 318 through...

    Complete the program that solves the Eight Queens problem in java only please (pages 318 through 320). The program’s output should look similar to: |1|0|0|0|0|0|0|0| |0|0|0|0|0|0|1|0| |0|0|0|0|1|0|0|0| |0|0|0|0|0|0|0|1| |0|1|0|0|0|0|0|0| |0|0|0|1|0|0|0|0| |0|0|0|0|0|1|0|0| |0|0|1|0|0|0|0|0| PlaceQueens(in currColumn:integer) //places queens in columns numbered currColumn through 8 If (currColumn>8){ The problem is solved } Else { While(unconsidered squares exist in curr column and the problem is unsolved ){ Determine the next square in column currColumn that is not under attack by a queen in an...

  • ================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...

  • I need help with the following and written in c++ thank you!: 1) replace the 2D...

    I need help with the following and written in c++ thank you!: 1) replace the 2D arrays with vectors 2) add a constructor to the Sudoku class that reads the initial configuration from a file 3) adds a function to the Sudoku class that writes the final Sudoku grid to a file or to the standard output device, cout. Sudoku.h #pragma once /* notes sudoku() default constructor precondition : none postcondition: grid is initialized to 0 sudoku(g[][9]) 1-parameter constructor precondition...

  • please explain/ comment 3. Eight Queens Write a program that places eight queens on a chessboard...

    please explain/ comment 3. Eight Queens Write a program that places eight queens on a chessboard (8 x 8 board) such that no queen is "attacking" another. Queens in chess can move vertically, horizontally, or diagonally. How you solve this problem is entirely up to you. You may choose to write a recursive program or an iterative (i.e., non-recursive) program. You will not be penalized/rewarded for choosing one method or another. Do what is easiest for you. 3.1. Output Below...

  • need help..... sudoku.h class sudoku { public: sudoku(); //default constructor //Postcondition: grid is initialized to 0...

    need help..... sudoku.h class sudoku { public: sudoku(); //default constructor //Postcondition: grid is initialized to 0 sudoku(int g[][9]); //constructor //Postcondition: grid = g void initializeSudokuGrid(); //Function to prompt the user to specify the numbers of the //partially filled grid. //Postcondition: grid is initialized to the numbers // specified by the user. void initializeSudokuGrid(int g[][9]); //Function to initialize grid to g //Postcondition: grid = g; void printSudokuGrid(); //Function to print the sudoku grid. bool solveSudoku(); //Funtion to solve the sudoku problem....

  • I need help as quick as possible, thanks beforehand. Please provide the test output The Lo...

    I need help as quick as possible, thanks beforehand. Please provide the test output The Lo Shu Magic Square is a grid with 3 rows and 3 columns shown below. 35 The Lo Shu Magic Square has the following properties: The grid contains the numbers 1 - 9 exactly The sum of each row, each column and each diagonal all add up to the same number. This is shown below: 15 4 92 15 - 81 + 15 15 15...

  • 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)<<"...

  • (C++) Two stacks of the same type are the same if they have the same number...

    (C++) Two stacks of the same type are the same if they have the same number of elements and their elements at the corresponding positions are the same. Overload the relational operator == for the class stackType that returns true if two stacks of the same type are the same; it returns false otherwise. Also, write the definition of the function template to overload this operator. Write a program to test the various overloaded operators and functions of classstackType. **Please...

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
ADVERTISEMENT