{ }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()・標準入力に渡されます(実行中に入力を求めません)。

$ 準備完了

コードを入力して解くにはパソコンで開いてください。モバイルでは問題と解答を見られます。

ほかの言語では?言語別の解答を見る · 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 には辞書がないので配列を先頭から探します。
Craykon は 辞書() で数え、キー一覧.並べ替え(多い順) のように比較関数の名前を渡します(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;}