Quick way of checking if a 2D array contains an element c#

Advertisements

I’m currently coding battleships as a part of a college project. The game works perfectly fine but I’d like to implement a way to check if a ship has been completely sunk. This is the method I’m currently using:

public static bool CheckShipSunk(string[,] board, string ship){
    for(int i = 0; i < board.GetLength(0); i++){
        for(int j = 0; j < board.GetLength(1); j++){
            if(board[i,j] == ship){return false;}
        }
    }
    return true;
}

The problem with this is that there are 5 ships, and this is very inefficient when checking hundreds of elements 5 times over, not to mention the sub-par quality of college computers. Is there an easier way of checking if a 2D array contains an element?

>Solution :

Use an arithmetic approach to loop-through with just 1 loop.

public static bool CheckShipSunk(string[,] board, string ship){
    int rows = board.GetLength(0);
    int cols = board.GetLength(1);
    for (int i = 0; i < rows * cols; i++) {
        int row = i / cols;
        int col = i % cols;
        if (board[row, col] == ship)
            return false;
    }
    return true;
}

But I am with Nysand on just caching and storing that information in cells. The above code although might work, is not recommended as it is still not as efficient

Leave a Reply Cancel reply