Solved Exercise Place n Bishops in a chessboard and find the positions where a Queen wouldn't be eated by any of the bishops in C++

Codemastr

CEO
Staff member
Administrator
Feb 1, 2019
36
1
238
Place n Bishops in a chessboard and find the positions where a Queen wouldn't be eated by any of the bishops in C++. Represent the bishops as "1" and the Queens by "8" in a 8x8 integer matrix and print it at the end showing the solutions.

C++:
/*
Author: Codemastr
Date: 13/05/2016
*/

#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;

int random(int from, int until) {
    if (from > until)
    {
        int x = from;
        from = until;
        until = x;
    }
    int dif = until - from;
    dif = abs(dif)+1;
    return rand()%dif + from;
}

int main() {
    srand(time(NULL));
    int n;
    bool bishop = true;
    while(bishop) {
        cout << "Input the number of bishops (5-24): ";
        cin >> n;
        if (n >= 5 && n<=24) {
            bishop = false;
        }
    }

    int m[8][8] = {{0}};
    int c[8][8] = {{0}};

    for (int i=0; i<n; i++) { // Place bishops and make sure they dont repeat
        int x = random(0,7);
        int y = random(0,7);
        if (m[x][y] == 1) {
            i--;
            continue;
        }
        else { // Cover diagonals
                m[x][y] = 1;
                c[x][y] = 1;
                for (int j=1; j<8; j++) {
                    if (x-j>=0 && y-j>=0)
                        c[x-j][y-j] = 1;

                    if (x-j>=0 && y+j<8)
                        c[x-j][y+j] = 1;

                    if (x+j<8 && y-j>=0)
                        c[x+j][y-j] = 1;

                    if (x+j<8 && y+j<8)
                        c[x+j][y+j] = 1;
                }
        }
    }

    for (int i=0; i<8; i++) {
        for (int j=0; j<8; j++) {
                cout << m[i][j] << " ";
        }
        cout << endl;
    }
    cout << endl;
    int rey = 0;
    for (int i=0; i<8; i++) {
        for (int j=0; j<8; j++) {
                if (c[i][j] == 0) {
                    m[i][j] = 8;
                    rey++;
                    cout << "[" << i << ":" << j << "]" << endl;
                }
        }
    }
    cout << endl;

    for (int h=0; h<8; h++) {
        for (int k=0; k<8; k++) {
                cout << m[h][k] << " ";
        }
        cout << endl;
    }
    cout << "Solutions: " << rey;

    return 0;

}
This would be the output:

32


Feel free to ask any questions or post a suggestion.