samedi 9 mai 2020

A C++ question that involves the use of for loops and if statements

This is a question from a coding practise paper. I have the answer however I would like to know how I can actually play the game, how can I input the data or how can I pass an argument to the parameter using the int main()

In the game connect 4, two players have to arrange their pieces on the board so that they have 4 of their pieces in a straight line. If a player gets 4 (or more) of their pieces in a straight line then they win. Different tiles are worth different values and certain positions on the board can double or even triple the value of the tile that is placed there.

For Example-

enter image description here

As we can example above, player a has got 4 of their pieces in a horizontal line and so player a has won. In the real version of the game the lines can be in any direction but for this questions we will only be looking for horizontal lines.

A Board class has been provided for you, you do not need to include it yourself. The class has the following attributes and methods.

class Board
{
public:
  const int size; // size of board on each side
  char get( int x, int y ) const; // gets the element at position x, y on the board. the top left position is 0, 0
};

Write a function called horizontal_winner.

  • The horizontal_winner will take one arguments.
  • The argument will be of type Board.
  • The argument will represent the pieces on the board.
  • Empty spaces on the board will be marked with a - (minus sign).
  • horizontal_winner will return an a single character
  • horizontal_winner will return a or b depending on which player has got 4 pieces in a horizontal line
  • horizontal_winner will return - (minus sign) if no player has a horizontal line.

For example:

enter image description here

The answer to this question is:

char horizontal_winner( Board board )
{
  int a, b;

  // for every row
  for( int y=0; y<board.size; ++y )
  {
    // reset counters
    a = b = 0;

    // for every column
    for( int x=0; x<board.size; ++x )
    {
      if( board.get(x,y) == 'a' )
        ++a;
      else // reset the counter
        a = 0;

      if( board.get(x,y) == 'b' )
        ++b;
      else // reset counter
        b = 0;

      if( a >= 4 ) return 'a';
      if( b >= 4 ) return 'b';
    }
  }

  return '-';
}

Aucun commentaire:

Enregistrer un commentaire