Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading