2

Trying to make connect4 and I want to check if a column (vertical) is full, so the easy way to do it would be in an if with [i, 1] != O && [i, 2] != O && [i, 3] != O et cetera, but isn't there a more efficient way to go on about this?

A board looks like:

O O O O O O O O
O O O O O O O O
O O O O O O O O
O O O O O O O O
O O O O O O O O
O O O O O O O O

The for-loop:

for (int i = row - 1; i > -1; i--)
{
     if (board[i, column].ToString() == "O" && beurt % 2 == 0)
     {
         board[i, column] = (Veld)player1.color;
         beurt += 1;
         break;
     }
     else if(board[i, column].ToString() == "O" && beurt % 2 == 1)
     {
             board[i, column] = (Veld)player2.color;
             beurt += 1;
             break;
     }
     else if(???)
     {
             //???
     }
}
1
  • Is the first row on the bottom? Commented Mar 25, 2019 at 19:45

2 Answers 2

4
bool isRowFull(char[,] array, int row)
{
    for(int i=0;i<array.GetLength(0); i++)
        if(array[row, i] == 'O') return false;
    return true;
}

And you can call it like:

bool isFull = isRowFull(board, 3); // check if row 3 is full 

or

if(isRowFull(board, 3))
{
    //your code
}

To Get First NonFull row:

int FirstNonFull(char[,] array)
{
    for(int i=0;i<array.GetLength(1);i++)
        if(!isRowFull(array, i)) return i;
    return -1; // -1 indicating that all rows are full (not found)
}
Sign up to request clarification or add additional context in comments.

9 Comments

You don't need any { } on the for-loop or if? Sorry I'm kinda new to this.
@Zheng-rongCai - Not if it's only one statement. I still put them a lot of the time for consistency/readability, but technically you don't need to here. It also gets confusing incredibly quickly if you nest multiple loops/ifs and don't use brackets...
as there is only one line of code inside for, its not necessary to have {} (but you could). if there were more lines of code {} were necessary
note that return true; is outside of for loop, meaning that if function didn't return anything inside for loop (no zeros exist) and reached this far, then it is full so return true
You should always put the brackets in, even for single lines. I see it all the time with my students; they have a single line, which works fine initially, but then later they decide to add more code and can't figure out where the bug is...
|
2

Similaraly you could use Linq to verify that All items at row equal O:

public static bool IsRowEmpty(char[,]board, int row)
{
    return Enumerable.Range(0, board.GetUpperBound(1)).All(col => board[row, col] == 'O');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.