'How do I print only 50 times the Array ChessBoard in this code?

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int ChessBoard[8][8];
void PrintBoard(int n)
{
    for(int i=0; i<=n-1; i++)
    {
        for(int j=0;j<=n-1; j++)
        {
            cout<<ChessBoard[i][j]<<" ";
        }
        cout<<endl;
    }   
    cout<<endl;
    cout<<endl;

}
bool isSafe(int col, int row, int n)
{
    for(int i=0;i<row; i++)
    {
        if(ChessBoard[i][col])
        {
            return true;
        }
    }
    for(int i=row, j=col; i>=0 && j>=0; i++,j--)
    {
        if(ChessBoard[i][j])
        {
            return false;
        }
    } 
    for(int i=row, j=col; i>=0 && j<n; i--,j--)
    {
        if(ChessBoard[i][j])
        {
            return false;
        }
    }
    return true;

}

bool Solution(int n, int row)
{
    if(n==row)
    {
        PrintBoard(n);
        return true;
    }
    bool result=false;
    for(int i=0;i<=n-1; i++)
    {
        if(isSafe(i,row,n))
        {
            ChessBoard[row][i]=1;
            result=Solution(n,row+1) || result;
            ChessBoard[row][i]=0;
        } 
    }
    return result;
}

int main()
{
    int n=8;
    for(int i=0; i<n; i++)
    {
        for(int j=0;j<n; j++)
        {
            ChessBoard[i][j]=0; 
        }
    }
    bool result = Solution(n,0);
    cout<<endl;
    return 0;
}

So basically what this code does is Not solving the 8-queens problem by printing 50 wrong answers to it (Where the queens attack each other). The issue so far is that it prints an infinite amount of wrong answers/arrays. I am trying for 2 days to make it print only 50 of them but I cant figure out where to put a while or for loop and nothing I did works. Thanks for your time, every help is appreciated.

c++


Solution 1:[1]

Add a counter in your print function, and make it to return a boolean value:

int counter = 0; //< new counter variable (in global scope)

bool PrintBoard(int n)
{
  if(counter < 50) {

    for(int i=0; i<=n-1; i++)
    {
        for(int j=0;j<=n-1; j++)
        {
            cout<<ChessBoard[i][j]<<" ";
        }
        cout<<endl;
    }
    cout<<endl;
    cout<<endl;

    counter++; //< increment counter

    return true; //< continue
  }

  return false; //< stop !
}

in your Solution function, return the value returned by PrintBoard so all process stops:

bool Solution(int n, int row)
{
    if(n==row)
    {
      return PrintBoard(n); //< stop process if 50 prints were reached
    }

    bool result = false;

    for(int i = 0; i <= n-1; i++)
    {
        if(isSafe(i,row,n))
        {
            ChessBoard[row][i]=1;
            result=Solution(n,row+1);
            ChessBoard[row][i]=0;
        }
    }
    return result;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1