[백준] 생태학 #4358

welchs·2022년 2월 2일
0

알고리즘

목록 보기
30/44
post-thumbnail

설명

HashMap을 이용해서 푸는 문제
JS는 기본 object를 사용했고, C++은 map STL을 사용해서 풀었다.
C++ map 사용법을 익힐 수 있었던 문제다.

Node.js 풀이

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));

C++ 풀이

#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;
}
profile
고수가 되고 싶은 조빱

0개의 댓글