Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hi I have a battleship search horizontal sweep algorithm. I was wondering how co

ID: 3710655 • Letter: H

Question

Hi I have a battleship search horizontal sweep algorithm. I was wondering how could I change it to make it more efficient? I am passing in a 25x25 map.

Here is what I have.

public class HorizontalSweep implements SearchStrategy {

int searchCount = 0;

int foundCount = 0;

String shipHead;

String shipTail;

String subHead;

String subTail;

public void search(int[][] map) {

System.out.println("Strategy: Horizontal Sweep");

for (int row = 0; row < map.length; row++) {

for (int col = 0; col < map[row].length; col++) {

if (map[row][col] != 0) {

foundCount++;

if (map[row][col] == 1) shipHead = "("+row+","+col+")";

else if (map[row][col] == 2) shipTail = "("+row+","+col+")";

else if (map[row][col] == 3) subHead = "("+row+","+col+")";

else if (map[row][col] == 4) subTail = "("+row+","+col+")";

}

searchCount++;

if (foundCount > 7) break;

}

if (foundCount > 7) break;

}

System.out.println("Number of cells searched: " + searchCount);

System.out.println("Carrier found: "+shipHead+" to "+shipTail+" Submarine found: "+subHead+" to "+subTail);

}

}

Explanation / Answer

From thecode provided by you, I could see that you want to search for Ship Head, Ship Tail, Sub Head, Sub Tail. Once you have found atleast 7 successful cells, you are done with the search.

Now as per you requirement, it is mandatory to iterate through every cell of the matrix until you have found 7 successful searches, you need to have one outer for loop to iterate through the rows and one inner for loop to iterate through the columns.

Your code, in my opinion, is efficient in terms of time complexity.