Amazon Interview Question
SDE1sCountry: United States
Interview Type: Phone Interview
class People {
String name;
String position;
String sex;
People(String name, String position, String sex){
this.name = name;
this.position = position;
this.sex = sex;
}
public String getAttribute(String attrName){
if(attrName == null)
return null;
if(attrName.equalsIgnoreCase("name"))
return name;
else if(attrName.equalsIgnoreCase("position"))
return position;
else if(attrName.equalsIgnoreCase("sex"))
return sex;
else
return null;
}
private static Map<List<String>, List<People>> groupAllByAttributes(List<People> friends, List<String> attributes){
Map<List<String>, List<People>> result = new HashMap<List<String>, List<People>>();
for(People p : friends){
List<String> atrb = new ArrayList<String>();
List<People> people;
for (String a : attributes){
atrb.add(p.getAttribute(a));
}
if(result.get(atrb) == null) {
people = new ArrayList<People>();
people.add(p);
result.put(atrb,people);
}
else{
people = result.get(atrb);
people.add(p);
result.put(atrb,people);
}
}
return result;
}
@Override
public String toString() {
return name;
}
public static void main(String [] args){
List<People> friends = new ArrayList<People>();
List<String> attributes = new ArrayList<String>();
attributes.add("sex");
attributes.add("position");
friends.add(new People("A", "Fin", "male"));
friends.add(new People("B", "Eng", "female"));
friends.add(new People("C", "Doc", "male"));
friends.add(new People("D", "Eng", "female"));
friends.add(new People("E", "Doc", "male"));
friends.add(new People("F", "Fin", "male"));
friends.add(new People("G", "Pharma", "male"));
friends.add(new People("H", "Pharma", "male"));
friends.add(new People("I", "Fin", "female"));
System.out.println(groupAllByAttributes(friends, attributes));
}
}
void GroupByMethod(std::list<people>& friends, std::list<string>& attributes) {
std::map<list<string>,list<people> > mapbyGroup;
std::map<list<string>,list<people> >::iterator it_map;
list<people>::iterator it;
list<string>::iterator it_str;
for (it = friends.begin(); it != friends.end(); it++) {
list<string> attribList;
for (it_str = attributes.begin(); it_str != attributes.end(); it_str++) {
attribList.push_back(it->getAttribute(*it_str));
}
it_map = mapbyGroup.find(attribList);
if (it_map != mapbyGroup.end()) {
it_map->second.push_back(*it);
} else {
list<people> peopleList;
peopleList.push_back(*it);
mapbyGroup.insert(std::pair<list<string>,list<people> >(attribList, peopleList));
}
}
friends.clear();
for (it_map = mapbyGroup.begin(); it_map != mapbyGroup.end(); it_map++) {
friends.insert(friends.end(), it_map->second.begin(), it_map->second.end());
}
}
you can use hash_table to do the group job.
- suwei19870312 December 01, 2014use the list2<sex, occupation> as the key, and the value will the index in the list1.
so after iterator the list1, you will get the group by result.