[Solved] How to check if a char in a 2d array appears more than once? c++


  1. Move you initialization of count to above the first for loop.
  2. Move the if statement after the end of the first for loop.

void board::winner(int x, int y)
{
int count = 0;

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

{
    for (int j = 0; j < row; xaxis++)
    {
        if (arr[i][j] == 'N')
        {
            count++;
        }            
    }
}
if (count == col) 
{
    cout << "P2 wins!";
}

}

You can make the loop more efficient by terminating the loops after the first duplicate is found:

for (int i = 0; i < col; ++i)
{
   for (int j = 0; j < row; ++j)
   {
      if (arr[i][j] == 'N')
      {
         ++count;
         if (count > 1)
         {
            break;
         }
      }
   }
   if (count > 1)
   {
      break;
   }
}

The above code will terminate as soon as the first duplicate is found, thus not searching the entire board.

solved How to check if a char in a 2d array appears more than once? c++