ALGORITHM (weight: 30%) A small directory is hard-coded as an array in the code: String names[] = { "Elon Musk", "Ken Howery", "Luke Nosek", "Max Levchin", "Peter Thiel" }; A requirement is to be able to extend this directory dynamically at runtime, without persistent storage. The directory can eventually grow to hundreds or thousands of names and must be searchable by first or last name. 1) What approach would you take? (Ans: HashMap) 2) Write an implementation for the add and search methods in pseudo-code using data structures you have in mind.
Utilisateur anonyme
import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class dictionary { HashMap> firstNameMap = new HashMap>(); HashMap> lastNameMap = new HashMap>(); public boolean add(String name) { if(name == null || name.isEmpty()) { return false; } String[] stringArr = name.split("\\s+"); String fName = stringArr[0]; String lName = stringArr[1]; if(firstNameMap.containsKey(fName)) { List temp = firstNameMap.get(fName); temp.add(name); } else { List temp = new ArrayList(); temp.add(name); firstNameMap.put(fName, temp); } if(lastNameMap.containsKey(lName)) { List temp = lastNameMap.get(lName); temp.add(name); } else { List temp = new ArrayList(); temp.add(name); lastNameMap.put(lName, temp); } return true; } public List searchByLastName(String lname) { if(lname == null) return null; return lastNameMap.get(lname); } public List searchByFirstName(String fname) { if(fname == null) return null; return firstNameMap.get(fname); } }