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 searched, found;

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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!