add examples in java 8 (#12)
* code for chapters 3-9 in Java * code for chapters 1 in Java * code for chapter 2 in Java * missing CheckVoter for chapter 5 in Java * add missing sample output for SetCovering as a comment
This commit is contained in:
committed by
Aditya Bhargava
parent
12265a8c61
commit
4631b7a156
@@ -0,0 +1,37 @@
|
||||
import java.util.*;
|
||||
|
||||
public class SetCovering {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Set<String> statesNeeded = new HashSet(Arrays.asList("mt", "wa", "or", "id", "nv", "ut", "ca", "az"));
|
||||
Map<String, Set<String>> stations = new LinkedHashMap<>();
|
||||
|
||||
stations.put("kone", new HashSet<>(Arrays.asList("id", "nv", "ut")));
|
||||
stations.put("ktwo", new HashSet<>(Arrays.asList("wa", "id", "mt")));
|
||||
stations.put("kthree", new HashSet<>(Arrays.asList("or", "nv", "ca")));
|
||||
stations.put("kfour", new HashSet<>(Arrays.asList("nv", "ut")));
|
||||
stations.put("kfive", new HashSet<>(Arrays.asList("ca", "az")));
|
||||
|
||||
Set<String> finalStations = new HashSet<String>();
|
||||
while (!statesNeeded.isEmpty()) {
|
||||
String bestStation = null;
|
||||
Set<String> statesCovered = new HashSet<>();
|
||||
|
||||
for (Map.Entry<String, Set<String>> station : stations.entrySet()) {
|
||||
Set<String> covered = new HashSet<>(statesNeeded);
|
||||
covered.retainAll(station.getValue());
|
||||
|
||||
if (covered.size() > statesCovered.size()) {
|
||||
bestStation = station.getKey();
|
||||
statesCovered = covered;
|
||||
}
|
||||
statesNeeded.removeIf(statesCovered::contains);
|
||||
|
||||
if (bestStation != null) {
|
||||
finalStations.add(bestStation);
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println(finalStations); // [ktwo, kone, kthree, kfive]
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user