Question: JAVA: This is a horizontal sweep strategy for finding battleship on a 25x25 board. The board is represented by a 25x25 integer array called map
JAVA:
This is a horizontal sweep strategy for finding battleship on a 25x25 board. The board is represented by a 25x25 integer array called map and is passed into the HorizontalSweep stretegy class. How could you change this code to make it more efficient?
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);
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
