{ }codelper
counting with a mapcustom sortingP0034

Word frequency ranking

A line of lowercase English words separated by single spaces is given.
For each distinct word print "word count" on its own line.
Print the most frequent words first; when counts are equal, use dictionary order of the words (a first; if one word is the start of another, the shorter comes first).

Input
1 to 1000 words, each 1 to 12 lowercase English letters
Output
one line per distinct word: the word and its count separated by one space
Example 1 · stdin
b a b a c
stdout
a 2
b 2
c 1
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

The trap is the order for equal counts.
Sorting by count alone keeps first-appearance order, and in Python sorting (count, word) with reverse=True puts the words from z down.
Two keys at once: 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 a qsort comparator with strcmp, C++ std::sort with a lambda.
Counting: Python Counter, Java merge(w, 1, Integer::sum), C# GetValueOrDefault, JS a Map rather than {} (counting in a plain object collides with "constructor" from Object.prototype).
C has no map, so it searches an array from the start.
Craykon counts with Dict() and passes a compare function's name, Keys.Sort(MostFirst) (like C#'s Sort(Comparison): negative if the first goes first, positive if the second does).

Pythonmain.py · 5 lines
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 lines
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 lines
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 lines
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 lines
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 lines
#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 lines
#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 lines
words = Console.ReadLine().Split();counts = Dict();foreach (w in words){    if (counts.Contains(w))    {        counts[w] = counts[w] + 1;    }    else    {        counts[w] = 1;    }}keys = counts.Keys;keys.Sort(많은것먼저);foreach (w in keys){    Console.WriteLine(w + " " + counts[w]);} // 개수가 많은 것 먼저, 같으면 사전 순많은것먼저(앞, 뒤){    if (counts[앞] != counts[뒤])    {        return counts[뒤] - counts[앞];    }    if (앞 < 뒤)    {        return -1;    }    return 1;}