Question
Can someone explain to me how this code is working to find the battleship on the given map? import java.util.HashSet; public class StrategicSearch implements SearchStrategy
Can someone explain to me how this code is working to find the battleship on the given map?
import java.util.HashSet;
public class StrategicSearch implements SearchStrategy {
String shipHead;
String shipTail;
String subHead;
String subTail;
HashSet
public void search(int[][] map) {
System.out.println("Strategy: Strategic Search");
searched = new HashSet
found = new HashSet
while (found.size() < 8) {
int row = (int) (Math.random() * map.length);
int col = (int) (Math.random() * map[0].length);
if (!searched.contains(row+" "+col)) {
if (!found.contains(row+" "+col) && map[row][col] != 0) {
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+")";
found.add(row+" "+col);
}
searched.add(row+" "+col);
}
}
System.out.println("Number of cells searched: " + searched.size());
System.out.println("Carrier found: "+shipHead+" to "+shipTail+" Submarine found: "+subHead+" to "+subTail);
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started