{ }codelper
사전으로 세기기준 정해 정렬P0034

단어 빈도 순위

영어 소문자 단어들이 빈칸 하나씩으로 나뉜 한 줄이 주어진다.
서로 다른 단어마다 "단어 개수"를 한 줄씩 출력하라.
많이 나온 단어부터 출력하고, 개수가 같으면 단어의 사전 순(a가 먼저, 앞부분이 같으면 짧은 것이 먼저)으로 출력한다.

입력
단어 수 1 ~ 1000, 각 단어는 영어 소문자 1 ~ 12글자
출력
서로 다른 단어 수만큼의 줄, 줄마다 단어와 개수를 빈칸 하나로
예시 1 · stdin
b a b a c
stdout
a 2
b 2
c 1
main.py
입력(stdin)

실행하면 이 줄들이 차례로 input()·표준 입력으로 들어가요(실행 중에 묻지 않아요).

$ 준비됐어요

코드를 입력해 풀려면 PC에서 열어 주세요. 모바일에서는 문제와 풀이를 볼 수 있어요.

다른 언어로는?언어별 풀이 보기 · 8개 언어 풀이

함정은 개수가 같을 때의 순서예요.
개수로만 정렬하면 처음 나온 차례가 남고, Python에서 (개수, 단어)를 reverse=True로 정렬하면 단어까지 z부터 나와요.
기준 두 개를 한 번에: Python key=lambda kv: (-kv[1], kv[0]), JS b[1] - a[1] || (a[0] < b[0] ? -1 : 1), Java comparingByValue().reversed().thenComparing(comparingByKey()), C# OrderByDescending(...).ThenBy(..., StringComparer.Ordinal), C qsort 비교 함수에서 strcmp, C++ std::sort에 람다.
세기는 Python Counter, Java merge(w, 1, Integer::sum), C# GetValueOrDefault, JS는 {} 대신 Map(빈 객체로 세면 "constructor"가 Object.prototype의 것과 부딪쳐요).
C에는 사전이 없어 배열을 처음부터 찾아요.
크레이콘은 사전()으로 세고 열쇠들.정렬(많은것먼저)처럼 비교 함수 이름을 넘겨요(C#의 Sort(Comparison)과 같아요: 앞이 먼저면 음수, 뒤가 먼저면 양수).

Pythonmain.py · 5 줄
from collections import Counter counts = Counter(input().split())for word, count in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])):    print(word, count)
JavaScriptmain.js · 5 줄
const words = require("fs").readFileSync(0, "utf8").trim().split(/\s+/);const counts = new Map();for (const w of words) counts.set(w, (counts.get(w) ?? 0) + 1);const entries = [...counts].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));console.log(entries.map(([w, c]) => `${w} ${c}`).join("\n"));
TypeScriptmain.ts · 6 줄
import { readFileSync } from "node:fs";const words: string[] = readFileSync(0, "utf8").trim().split(/\s+/);const counts = new Map<string, number>();for (const w of words) counts.set(w, (counts.get(w) ?? 0) + 1);const entries: [string, number][] = [...counts].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));console.log(entries.map(([w, c]) => `${w} ${c}`).join("\n"));
JavaMain.java · 21 줄
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map; public class Main {    public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        Map<String, Integer> counts = new HashMap<>();        for (String w : in.readLine().trim().split("\\s+")) counts.merge(w, 1, Integer::sum);        List<Map.Entry<String, Integer>> entries = new ArrayList<>(counts.entrySet());        entries.sort(Map.Entry.<String, Integer>comparingByValue().reversed()                .thenComparing(Map.Entry.comparingByKey()));        StringBuilder out = new StringBuilder();        for (Map.Entry<String, Integer> e : entries) out.append(e.getKey()).append(' ').append(e.getValue()).append('\n');        System.out.print(out);    }}
C#Main.cs · 15 줄
using System;using System.Collections.Generic;using System.Linq; class Program{    static void Main()    {        var counts = new Dictionary<string, int>();        foreach (string w in Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries))            counts[w] = counts.GetValueOrDefault(w) + 1;        var sorted = counts.OrderByDescending(kv => kv.Value).ThenBy(kv => kv.Key, StringComparer.Ordinal);        foreach (var kv in sorted) Console.WriteLine($"{kv.Key} {kv.Value}");    }}
C++main.cpp · 17 줄
#include <algorithm>#include <iostream>#include <string>#include <unordered_map>#include <vector> int main() {    std::unordered_map<std::string, int> counts;    std::string w;    while (std::cin >> w) counts[w]++;    std::vector<std::pair<std::string, int>> entries(counts.begin(), counts.end());    std::sort(entries.begin(), entries.end(), [](const auto& a, const auto& b) {        if (a.second != b.second) return a.second > b.second;        return a.first < b.first;    });    for (const auto& [word, count] : entries) std::cout << word << ' ' << count << '\n';}
Cmain.c · 33 줄
#include <stdio.h>#include <stdlib.h>#include <string.h> struct Entry {    char word[13];    int count;}; static int by_count_then_word(const void *pa, const void *pb) {    const struct Entry *a = pa, *b = pb;    if (a->count != b->count) return b->count - a->count;    return strcmp(a->word, b->word);} int main(void) {    static struct Entry entries[1000];    int n = 0;    char w[13];    while (scanf("%12s", w) == 1) {        int i = 0;        while (i < n && strcmp(entries[i].word, w) != 0) i++;        if (i == n) {            strcpy(entries[n].word, w);            entries[n].count = 0;            n++;        }        entries[i].count++;    }    qsort(entries, n, sizeof entries[0], by_count_then_word);    for (int i = 0; i < n; i++) printf("%s %d\n", entries[i].word, entries[i].count);    return 0;}
Craykonmain.cray · 33 줄
words = 콘솔.줄읽기().나누기();counts = 사전();각각 (w 에서 words){    만약 (counts.있나(w))    {        counts[w] = counts[w] + 1;    }    아니면    {        counts[w] = 1;    }}keys = counts.열쇠목록;keys.정렬(많은것먼저);각각 (w 에서 keys){    콘솔.쓰기(w + " " + counts[w]);} // 개수가 많은 것 먼저, 같으면 사전 순많은것먼저(앞, 뒤){    만약 (counts[앞] != counts[뒤])    {        돌려주기 counts[뒤] - counts[앞];    }    만약 (앞 < 뒤)    {        돌려주기 -1;    }    돌려주기 1;}