생태학
풀이
- 나무 종 이름이 주어지고, 전체에서 그 종이 차지하는 비율을 구해야 하기 때문에, 종 이름과 갯수를 저장할 수 있는 HashMap 자료구조를 이용해야겠다고 생각함.
- 근데 이 문제 입력이 최대 10,000개이고 끝나는 조건이 없었다. 어떡하지.. ? 입력에서 막힘
- 구글링 결과,
input==null || input.length()==0
이면 입력받는 while문을 끝내는 것으로 구현
- 그리고, 결과 출력시, 비율을 "백분율로 소수점 4째자리까지 반올림" 해야 하는 조건이 존재.
- 처음에 별 생각없이 round로 처리하려 함. 그치만 Math.round
함수는 소수점아래가 0일경우 절삭을 한다는 특징이 있었다. 때문에 String.format("%.4f",avg)
을 사용했다.
- 또, 출력시 알파벳순으로 출력해야 하는 조건이 있었기 때문에 HashMap의 Key값을 ArrayList로 꺼낸 다음, 오름차순으로 정렬했다.
Collections.sort(keySet)
코드
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
HashMap<String,Integer> map = new HashMap<>();
String input = "";
int total = 0;
while(true){
input = br.readLine();
if(input==null||input.length()==0) break;
total++;
map.put(input,map.getOrDefault(input,0)+1);
}
List<String> keySet = new ArrayList<>(map.keySet());
Collections.sort(keySet);
StringBuilder sb = new StringBuilder();
for(String key: keySet){
int cnt = map.get(key);
double avg = (double)(cnt*100.0)/total;
sb.append(key+" "+String.format("%.4f",avg)+"\n");
}
System.out.println(sb.toString());
}
}