[BCG Gamma] 真人機考紀錄
檸檬爸有機會參加 BCG Gamma Machine Learning Engineer 的面試測驗,到達第三關之後沒有順利完成測驗,所以利用這一篇的機會做一個整理,BCG Gamma 的第三關機考進行的方式是遠端有一個工程師出題目考你,你直接在電腦前面作答並且跟他討論。
檸檬爸遇到的題目:
Given a arbitrary String, print out the frequency of each character (considering lower and uppercase and 0-9) with sorting the largest number of character at the beginning. For example,
“abbacbcaa” =>
‘a’: 4, ‘b’: 3, ‘c’:2
“Today’s weather is very good” =>
‘e’: 3, ‘o’: 3, ‘r’:2, ‘a’: 2, ‘y’: 2, ‘s’: 2, ‘d’: 2, ‘T’: 1, ‘w’: 1, ‘t’: 1, ‘h’: 1, ‘i’: 1, ‘v’: 1, ‘g’: 1
受試者可以使用任何的程式語言完成以上的,主要是要看受試者以下的觀念:
- 使用 Collections
- 使用 Regular Expression (Regex)
- 使用 Sorting
檸檬爸提供的參考答案:
public class EnterPoint {
public static void main(String[] args){
printOut(countFrequency("abbacbcaa"));
printOut(countFrequency("Today's weather is very good"));
}
public static Map<String, Integer> countFrequency(String input){
Map<String, Integer> output = new HashMap<String, Integer>();
char[] chars = input.toCharArray();
for (int i=0; i<chars.length; i++) {
String key = Character.toString(chars[i]);
if (key.matches("[a-zA-Z]")){
if (output.containsKey(key)) {
int newCount = output.get(key) + 1;
output.put(key, newCount);
} else {
output.put(key, 1);
}
}
}
return output;
}
public static void printOut(Map<String, Integer> input){
List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(input.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, Integer> mapping : list) {
builder.append("'").append(mapping.getKey()).append("': ").append(mapping.getValue()).append(", ");
}
String output = builder.toString();
System.out.println(output.substring(0,output.length()-2));
}
}
輸入以上的 String 做測試,我們得到以下的輸出:
Connected to the target VM, address: '127.0.0.1:62629', transport: 'socket'
'a': 4, 'b': 3, 'c': 2
'e': 3, 'o': 3, 'a': 2, 'd': 2, 'r': 2, 's': 2, 'y': 2, 'g': 1, 'h': 1, 'i': 1, 'T': 1, 't': 1, 'v': 1, 'w': 1