Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Programming The Perl DBI Database Programming With Perl

Authors: Tim Bunce, Alligator Descartes

1st Edition

1565926994, 978-1565926998

More Books

Students also viewed these Databases questions