HashMap을 이용해서 푸는 문제
JS는 기본 object를 사용했고, C++은 map STL을 사용해서 풀었다.
C++ map 사용법을 익힐 수 있었던 문제다.
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n').map((v) => v.trim());
const solution = (names) => {
const dict = {};
let total = 0;
names.forEach((name) => {
if (!dict[name]) dict[name] = 0;
dict[name] += 1;
total += 1;
});
return Object.keys(dict)
.sort()
.map((key) => `${key} ${((dict[key] / total) * 100).toFixed(4)}`)
.join('\n');
};
console.log(solution(input));
#include<bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
map<string, int> M;
string str;
int total = 0;
while(getline(cin, str)) {
M[str] += 1;
total += 1;
}
cout.precision(4);
cout << fixed;
for (auto &[k, v] : M) {
cout << k << ' ' << 100.0*v/total << '\n';
}
return 0;
}