Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Suppose you want to add some more to the SleighTrack class we wrote in class: A.

ID: 3595338 • Letter: S

Question

Suppose you want to add some more to the SleighTrack class we wrote in class:

A. Write a public boolean allVisited(Set<Location> locations) method that returns true iff the current SleighTrack instance has visited all of the given locations. (It is possible to do this one without using a for loop.)

B. Write a public int mostPresents() method that returns the highest number of presents delivered to a single location in the current SleighTrack. (It is possible to do this one without a for loop, but you’ll need to read over the instance method of Map and the static methods of Collections to see how.)

C. Write a public void presentsToCoal(Set<Location> locations) method that removes the given locations from the current SleighTrack, if they are in it. (It is possible to do this one without a for loop, but you’ll need to carefully read over the instance methods of Map to see how.)

Thank you!

Explanation / Answer

package stopwatch;

import java.util.Collections;

import java.util.HashMap;

import java.util.Map;

import java.util.Set;

public class SleighTrack {

private Map<Location, Integer> locationCount;

public SleighTrack(String directions) {

locationCount = new HashMap<Location, Integer>();

locationCount.put(new Location(0, 0), 1);

int x = 0;

int y = 0;

for (int i = 0; i < directions.length(); i++) {

if (directions.charAt(i) == '>') {

x += 1;

} else if (directions.charAt(i) == '<') {

x -= 1;

} else if (directions.charAt(i) == '^') {

y += 1;

} else if (directions.charAt(i) == 'v') {

y -= 1;

}

else {

throw new IllegalArgumentException();

}

}

Location loc = new Location(x, y);

int t = locationCount.getOrDefault(loc, 0);

locationCount.put(loc, t+1);

}

// keySet() will give us all the visited locations in the Map and equals will return true only if all the visited locations set is equals to the input location set

public boolean allVisited(Set<Location> locations) {

return locationCount.keySet().equals(locations);

}

// values() will give us number of times an present sent to a location in the Map, and Max method of Collections will give us the maximum number in the values list.

public int mostPresents() {

return Collections.max(locationCount.values());

}

// keySet() will give us all the visited locations in the Map and removeAll will remove the Map entries from Map whose locations are in the set locations.

public void presentsToCoal(Set<Location> locations) {

locationCount.keySet().removeAll(locations);

}

  

  

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote