Search code examples
cnested-loops

How to check for n consecutive same characters in row in c


So my assignment is to write a program for Connect-N, which is basically the game Connect-4 but where the user specifies the number of rows and columns (doesn't have to be square) and specifies the number of consecutive pieces to win (this doesn't have to fit on the board). For example, if the user specifies a 3x3 board, they can also say 4 consecutive pieces are needed to win.

I'm having trouble writing a program to check for a row win, where the player wins the game completely horizontally. Here's what I have so far:

bool horizontalWin(char **board, const int numRows, 
const int numCols, const char blankSpace, const int numToWin) {
  if((numCols - numToWin) < 0) {
      return false;
  }
  else {
    for (int row = 0; row < numRows; ++row) {
      for (int col = 0; col <= numCols-numToWin; ++col) {
        ///This is where I need help
      }
    }
  }
return false;
}

Just for reference: the variable blankSpace is a '*' and is used to denote a blank space on the board.

My idea was to have a nested for loop that started at column 0 and then checked far enough forward to see if they were all identical characters, but I can't seem to figure out how to accomplish this. Can someone point me in the right direction?


Solution

  • Count the number of matches, or reset the count when there is no match.

    Assuming board[row][col], and that the color you check is user1

    for (int row = 0; row < numRows; ++row) {
        int match = 0;
        for (int col = 0; col <= numCols-numToWin; ++col) {
            if (board[row][col] != user1) match = 0;
            else {
                match++;
                if (match >= numToWin) return true;
            }
        }
    }
    

    Note that you could do if (++match >= numToWin) return true; to save a line (if you feel this being readable).

    This is not in the problem description, but if you have two players, there should be 3 colors, say blankSpace, user1, and user2. The program above checks if user1 wins.

    So you could add an argument to the function to tell which color you are testing for a win (say colorCheck), the whole function becomes

    bool horizontalWin(char **board, const int numRows, 
    const int numCols, const char blankSpace, const int numToWin, const in colorCheck) {
      if((numCols - numToWin) < 0) {
          return false;
      }
      else {
         for (int row = 0; row < numRows; ++row) {
            for (int col = 0; col <= numCols-numToWin; ++col) {
               if (board[row][col] != colorCheck) match = 0;
               else {
                  match++;
                  if (match >= numToWin) return true;
               }
            }
         }
      }
      return false;
    }