JAVA: This is a horizontal sweep strategy for finding battleship on a 25x25 boar
ID: 3710667 • Letter: J
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 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);
}
}
Explanation / Answer
here is your modified code : --------->>>>>>>>>
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+")";
foundCount++;
col++;
}
if (map[row][col] == 3){subHead = "("+row+","+col+")";foundCount++;col++}
if (map[row][col] == 4){subTail = "("+row+","+col+")";foundCount++;col++}
if (map[row][col] == 2){shipTail = "("+row+","+col+")";foundCount++;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);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.