Programming Search⌘K

Taskintro

Count the items of each kind

Also called count occurrences, frequency count, histogram of a list, tally, Counter, count distinct items.

Count how many times each distinct item is in a list of integers, and give the counts in ascending order of the item.

Task

Count how many times each distinct item is in a list of integers. The function count_items(items) returns one pair (item, count) for each distinct item, in ascending order of the item. For example, count_items([3, 1, 3, 2, 1, 3]) is [(1, 2), (2, 1), (3, 3)].

The items are 32-bit signed integers, and the list can be empty. Then the result is an empty list. Each count is at least 1, because an item that is not in the list has no pair.

Solutions

Language Count the items, then put them in order
Python sorted(Counter(items).items())
JavaScript, TypeScript a Map, then sort with a function that compares the numbers
Java a TreeMap and merge(x, 1, Integer::sum)
C# GroupBy, OrderBy and Count
Go a map, then a sorted slice of the keys
Rust a BTreeMap and entry(x).or_insert(0)
C a sorted copy of the items, then a count of each run of equal items
C++ a std::map and ++counts[x]
Bash an associative array, then sort -n
  • The order. The task gives the pairs in ascending order of the item. Thus the result does not depend on the order of the keys in a hash map. Java, Rust and C++ use a map that keeps its keys in order. The other solutions sort the keys.
  • C. C has no map in its standard library. The solution sorts a copy of the items with qsort, so equal items are next to each other. Then one loop counts each run of equal items. The caller gives an output array with room for n pairs, because each item can be different.
  • Bash. The function prints one line ITEM COUNT for each distinct item. It prints nothing for an empty list.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • empty: an empty list gives an empty list.
  • single: [7] gives [(7, 1)].
  • negative: [-1, 2, -1, 0] gives [(-1, 2), (0, 1), (2, 1)].
  • distinct: when no two items are equal, each count is 1.
  • order: [9, 8, 9] gives [(8, 1), (9, 2)], in the order of the items, not the order of the first time that each item is in the list.
  • zero: 0 is an item, and its count is 2 in [0, 0].
  • extremes: -2147483648 and 2147483647 are items.

Pitfalls

  • Python a dict raises KeyError for a missing key. counts[x] += 1 reads counts[x] first. A Counter has "a dictionary interface except that they return a zero count for missing items instead of raising a KeyError"1. A read of a missing item does not add it, so len(c) stays 1:
from collections import Counter

counts = {}
try:
    for x in [1, 1]:
        counts[x] += 1
except KeyError as e:
    print("KeyError", e)

c = Counter([1, 1])
print(c[5], 5 in c, len(c))
Output
KeyError 1
0 False 1
  • JavaScript the keys of an object are strings in a special order. For an object, "all non-negative integer keys (those that can be array indices) will be traversed first in ascending order by value, then other string keys in ascending chronological order of property creation"2. In the example, the keys are '1', '2' and '-1', as strings. A Map keeps the numbers and the order of insertion:
const obj = {};
for (const x of [2, -1, 1, 2]) {
  obj[x] = (obj[x] ?? 0) + 1;
}
console.log(Object.keys(obj));

const map = new Map();
for (const x of [2, -1, 1, 2]) {
  map.set(x, (map.get(x) ?? 0) + 1);
}
console.log([...map.keys()]);
Output
[ '1', '2', '-1' ]
[ 2, -1, 1 ]
  • Java get gives null for a missing key. get "Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key"3. Thus counts.get(1) + 1 throws a NullPointerException when it unboxes the null. Use merge:
import java.util.Map;
import java.util.TreeMap;

public class Main {
  public static void main(String[] args) {
    Map<Integer, Integer> counts = new TreeMap<>();
    try {
      counts.put(1, counts.get(1) + 1);
    } catch (NullPointerException e) {
      System.out.println("NullPointerException");
    }
    for (int x : new int[] {1, 1}) {
      counts.merge(x, 1, Integer::sum);
    }
    System.out.println(counts);
  }
}
Output
NullPointerException
{1=2}
  • C# the indexer throws for a missing key. The indexer throws KeyNotFoundException when "The property is retrieved and key does not exist in the collection"4. counts[1]++ reads the value first. Use GetValueOrDefault:
using System;
using System.Collections.Generic;

var counts = new Dictionary<int, int>();
try
{
    counts[1]++;
}
catch (KeyNotFoundException)
{
    Console.WriteLine("KeyNotFoundException");
}
foreach (int x in new[] { 1, 1 })
{
    counts[x] = counts.GetValueOrDefault(x) + 1;
}
Console.WriteLine(counts[1]);
Output
KeyNotFoundException
2
  • Go a write to a nil map panics. "A nil map is equivalent to an empty map except that no elements may be added."5 In the example, a read of counts[5] gives 0, but counts[5]++ panics. Make the map with make:
package main

import "fmt"

func main() {
	var counts map[int]int
	fmt.Println(counts[5], len(counts))
	defer func() {
		fmt.Println("panic:", recover())
	}()
	counts[5]++
}
Output
0 0
panic: assignment to entry in nil map
  • Rust a HashMap gives its keys in an arbitrary order. keys gives "An iterator visiting all keys in arbitrary order"6. A BTreeMap gives its keys in ascending order, so the result does not need a sort. get gives None for a missing key:
use std::collections::BTreeMap;

fn main() {
    let mut counts = BTreeMap::new();
    for x in [2, -1, 0, 2] {
        *counts.entry(x).or_insert(0) += 1;
    }
    println!("{:?}", counts);
    println!("{:?}", counts.get(&5));
}
Output
{-1: 1, 0: 1, 2: 2}
None
  • C qsort changes the input. qsort "Sorts the given array pointed to by ptr in ascending order"7, in place. In the example, the order of items changes. The solution sorts a copy, so the input of the caller does not change:
#include <stdio.h>
#include <stdlib.h>

static int cmp_int(const void *a, const void *b) {
    int x = *(const int *)a;
    int y = *(const int *)b;
    return (x > y) - (x < y);
}

int main(void) {
    int items[] = {3, 1, 2, 1};
    size_t n = sizeof items / sizeof items[0];
    qsort(items, n, sizeof items[0], cmp_int);
    for (size_t i = 0; i < n; i++) {
        printf(i + 1 < n ? "%d " : "%d\n", items[i]);
    }
    return 0;
}
Output
1 1 2 3
  • C++ operator[] adds a missing key. operator[] gives a reference to the value, "performing an insertion if such key does not already exist"8. In the example, the test counts[5] == 0 adds the key 5, so the size changes from 1 to 2. To test for a key, use contains or find:
#include <iostream>
#include <map>

int main() {
    std::map<int, int> counts{{1, 2}};
    std::cout << counts.size() << '\n';
    if (counts[5] == 0) {
        std::cout << "5 is not in the list\n";
    }
    std::cout << counts.size() << '\n';
    std::cout << counts.contains(7) << ' ' << counts.size() << '\n';
}
Output
1
5 is not in the list
2
0 2
  • Bash an indexed array counts back from the end for a negative key. "Associative arrays are created using declare -A name"9. Without -A, the array is an indexed array. For an index less than zero, "negative indices count back from the end of the array"9. In the example, plain[-1]=1 fails because the array is empty. With declare -A, -1 is a key:
#!/usr/bin/env bash
plain=()
(plain[-1]=1) 2>/dev/null
echo "status $?"
declare -A counts=()
counts[-1]=1
echo "${!counts[@]}"
Output
status 1
-1

Code

The build runs the native tests of each language in a pinned toolchain.

count_items.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/count-the-items-of-each-kind/.

from collections import Counter


def count_items(items: list[int]) -> list[tuple[int, int]]:
    """Return one (item, count) pair for each distinct item, in ascending order of the item."""
    return sorted(Counter(items).items())
test_count_items.py 24 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/count-the-items-of-each-kind/.

import pytest

from count_items import count_items

CASES = {
    "mixed": ([3, 1, 3, 2, 1, 3], [(1, 2), (2, 1), (3, 3)]),
    "same": ([5, 5, 5], [(5, 3)]),
    "empty": ([], []),
    "single": ([7], [(7, 1)]),
    "negative": ([-1, 2, -1, 0], [(-1, 2), (0, 1), (2, 1)]),
    "distinct": ([4, 2, 9], [(2, 1), (4, 1), (9, 1)]),
    "order": ([9, 8, 9], [(8, 1), (9, 2)]),
    "zero": ([0, 0], [(0, 2)]),
    "extremes": ([2147483647, -2147483648, 2147483647], [(-2147483648, 1), (2147483647, 2)]),
}


@pytest.mark.parametrize("name", CASES)
def test_count_items(name):
    items, want = CASES[name]
    assert count_items(items) == want
count_items.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-items-of-each-kind/.

#include "count_items.hpp"

#include <map>

std::vector<std::pair<int, std::size_t>> count_items(std::span<const int> items) {
    // A std::map keeps its keys in ascending order.
    std::map<int, std::size_t> counts;
    for (int x : items) {
        ++counts[x];
    }
    return {counts.begin(), counts.end()};
}
count_items.hpp 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-items-of-each-kind/.

#pragma once

#include <cstddef>
#include <span>
#include <utility>
#include <vector>

// count_items returns one (item, count) pair for each distinct item, in
// ascending order of the item.
std::vector<std::pair<int, std::size_t>> count_items(std::span<const int> items);
test_count_items.cpp 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-items-of-each-kind/.

#include "count_items.hpp"

#include <cstddef>
#include <iostream>
#include <string_view>
#include <utility>
#include <vector>

static int failures = 0;

using Pairs = std::vector<std::pair<int, std::size_t>>;

static void check(std::string_view name, const std::vector<int> &items, const Pairs &want) {
    if (count_items(items) != want) {
        std::cerr << "case " << name << " failed\n";
        failures++;
    }
}

int main() {
    check("mixed", std::vector<int>{3, 1, 3, 2, 1, 3}, Pairs{{1, 2}, {2, 1}, {3, 3}});
    check("same", std::vector<int>{5, 5, 5}, Pairs{{5, 3}});
    check("empty", std::vector<int>{}, Pairs{});
    check("single", std::vector<int>{7}, Pairs{{7, 1}});
    check("negative", std::vector<int>{-1, 2, -1, 0}, Pairs{{-1, 2}, {0, 1}, {2, 1}});
    check("distinct", std::vector<int>{4, 2, 9}, Pairs{{2, 1}, {4, 1}, {9, 1}});
    check("order", std::vector<int>{9, 8, 9}, Pairs{{8, 1}, {9, 2}});
    check("zero", std::vector<int>{0, 0}, Pairs{{0, 2}});
    check("extremes", std::vector<int>{2147483647, (-2147483647 - 1), 2147483647}, Pairs{{(-2147483647 - 1), 1}, {2147483647, 2}});
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
CountItems.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-items-of-each-kind/.

import java.util.Map;
import java.util.TreeMap;

final class CountItems {
  private CountItems() {}

  /** Returns one {item, count} pair for each distinct item, in ascending order of the item. */
  static int[][] countItems(int[] items) {
    // A TreeMap keeps its keys in ascending order.
    Map<Integer, Integer> counts = new TreeMap<>();
    for (int x : items) {
      counts.merge(x, 1, Integer::sum);
    }
    int[][] out = new int[counts.size()][];
    int i = 0;
    for (Map.Entry<Integer, Integer> e : counts.entrySet()) {
      out[i++] = new int[] {e.getKey(), e.getValue()};
    }
    return out;
  }
}
CountItemsTest.java 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-items-of-each-kind/.

import static org.junit.jupiter.api.Assertions.assertArrayEquals;

import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class CountItemsTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("mixed", new int[] {3, 1, 3, 2, 1, 3}, new int[][] {{1, 2}, {2, 1}, {3, 3}}),
        Arguments.of("same", new int[] {5, 5, 5}, new int[][] {{5, 3}}),
        Arguments.of("empty", new int[] {}, new int[][] {}),
        Arguments.of("single", new int[] {7}, new int[][] {{7, 1}}),
        Arguments.of("negative", new int[] {-1, 2, -1, 0}, new int[][] {{-1, 2}, {0, 1}, {2, 1}}),
        Arguments.of("distinct", new int[] {4, 2, 9}, new int[][] {{2, 1}, {4, 1}, {9, 1}}),
        Arguments.of("order", new int[] {9, 8, 9}, new int[][] {{8, 1}, {9, 2}}),
        Arguments.of("zero", new int[] {0, 0}, new int[][] {{0, 2}}),
        Arguments.of("extremes", new int[] {2147483647, -2147483648, 2147483647}, new int[][] {{-2147483648, 1}, {2147483647, 2}}));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void countItems(String name, int[] items, int[][] want) {
    // assertArrayEquals compares the inner arrays by their items.
    assertArrayEquals(want, CountItems.countItems(items));
  }
}
count_items.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-items-of-each-kind/.

#include "count_items.h"

#include <stdlib.h>
#include <string.h>

// cmp_int compares two ints. It does not subtract them, because the
// subtraction can overflow.
static int cmp_int(const void *a, const void *b) {
    int x = *(const int *)a;
    int y = *(const int *)b;
    return (x > y) - (x < y);
}

size_t count_items(const int *items, size_t n, struct item_count *out) {
    if (n == 0) {
        return 0;
    }
    // qsort sorts in place, so sort a copy.
    int *s = malloc(n * sizeof *s);
    if (s == NULL) {
        return 0;
    }
    memcpy(s, items, n * sizeof *s);
    qsort(s, n, sizeof *s, cmp_int);
    size_t k = 0;
    for (size_t i = 0; i < n; i++) {
        if (k > 0 && out[k - 1].item == s[i]) {
            out[k - 1].count++;
        } else {
            out[k].item = s[i];
            out[k].count = 1;
            k++;
        }
    }
    free(s);
    return k;
}
count_items.h 19 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-items-of-each-kind/.

#ifndef COUNT_ITEMS_H
#define COUNT_ITEMS_H

#include <stddef.h>

struct item_count {
    int item;
    size_t count;
};

// count_items writes one pair for each distinct item of items[0..n) to out, in
// ascending order of the item. out must have room for n pairs. It returns the
// number of pairs, or 0 if n is 0. It does not change items.
size_t count_items(const int *items, size_t n, struct item_count *out);

#endif
test_count_items.c 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-items-of-each-kind/.

#include "count_items.h"

#include <stdio.h>

static int failures = 0;

#define L(...) {__VA_ARGS__}

// An empty list has a 0 in it, because C has no empty array. The counts give
// the real lengths.
#define CHECK(name, n, given, m, ...)                                          \
    do {                                                                       \
        const int g[] = given;                                                 \
        const struct item_count w[] = {__VA_ARGS__};                           \
        struct item_count out[sizeof g / sizeof g[0]];                         \
        const size_t want_n = m;                                               \
        size_t k = count_items(g, n, out);                                     \
        int ok = k == want_n;                                                  \
        for (size_t i = 0; ok && i < want_n; i++) {                            \
            ok = out[i].item == w[i].item && out[i].count == w[i].count;       \
        }                                                                      \
        if (!ok) {                                                             \
            fprintf(stderr, "case %s failed\n", name);                         \
            failures++;                                                        \
        }                                                                      \
    } while (0)

int main(void) {
    CHECK("mixed", 6, L(3, 1, 3, 2, 1, 3), 3, {1, 2}, {2, 1}, {3, 3});
    CHECK("same", 3, L(5, 5, 5), 1, {5, 3});
    CHECK("empty", 0, L(0), 0, {0, 0});
    CHECK("single", 1, L(7), 1, {7, 1});
    CHECK("negative", 4, L(-1, 2, -1, 0), 3, {-1, 2}, {0, 1}, {2, 1});
    CHECK("distinct", 3, L(4, 2, 9), 3, {2, 1}, {4, 1}, {9, 1});
    CHECK("order", 3, L(9, 8, 9), 2, {8, 1}, {9, 2});
    CHECK("zero", 2, L(0, 0), 1, {0, 2});
    CHECK("extremes", 3, L(2147483647, (-2147483647 - 1), 2147483647), 2, {(-2147483647 - 1), 1}, {2147483647, 2});
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
CountItems.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-items-of-each-kind/.

using System.Linq;

public static class CountItems
{
    // Count returns one (item, count) pair for each distinct item, in ascending order of the item.
    public static (int Item, int Count)[] Count(int[] items)
    {
        return items
            .GroupBy(x => x)
            .OrderBy(g => g.Key)
            .Select(g => (g.Key, g.Count()))
            .ToArray();
    }
}
CountItemsTests.cs 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-items-of-each-kind/.

using Xunit;

public sealed class CountItemsTests
{
    public static TheoryData<string, int[], (int, int)[]> Cases => new()
    {
        { "mixed", new int[] { 3, 1, 3, 2, 1, 3 }, new (int, int)[] { (1, 2), (2, 1), (3, 3) } },
        { "same", new int[] { 5, 5, 5 }, new (int, int)[] { (5, 3) } },
        { "empty", new int[0], new (int, int)[0] },
        { "single", new int[] { 7 }, new (int, int)[] { (7, 1) } },
        { "negative", new int[] { -1, 2, -1, 0 }, new (int, int)[] { (-1, 2), (0, 1), (2, 1) } },
        { "distinct", new int[] { 4, 2, 9 }, new (int, int)[] { (2, 1), (4, 1), (9, 1) } },
        { "order", new int[] { 9, 8, 9 }, new (int, int)[] { (8, 1), (9, 2) } },
        { "zero", new int[] { 0, 0 }, new (int, int)[] { (0, 2) } },
        { "extremes", new int[] { 2147483647, -2147483648, 2147483647 }, new (int, int)[] { (-2147483648, 1), (2147483647, 2) } },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, int[] items, (int, int)[] want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, CountItems.Count(items));
    }
}
count_items.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-items-of-each-kind/.

/**
 * @param {number[]} items
 * @returns {[number, number][]}
 */
export function countItems(items) {
  // A Map keeps the numbers as numbers. The keys of an object are strings.
  const counts = new Map();
  for (const x of items) {
    counts.set(x, (counts.get(x) ?? 0) + 1);
  }
  // Compare the numbers. sort() without a function compares strings.
  return [...counts].sort((p, q) => p[0] - q[0]);
}
count_items.test.js 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-items-of-each-kind/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { countItems } from "./count_items.js";

const cases = [
  ["mixed", [3, 1, 3, 2, 1, 3], [[1, 2], [2, 1], [3, 3]]],
  ["same", [5, 5, 5], [[5, 3]]],
  ["empty", [], []],
  ["single", [7], [[7, 1]]],
  ["negative", [-1, 2, -1, 0], [[-1, 2], [0, 1], [2, 1]]],
  ["distinct", [4, 2, 9], [[2, 1], [4, 1], [9, 1]]],
  ["order", [9, 8, 9], [[8, 1], [9, 2]]],
  ["zero", [0, 0], [[0, 2]]],
  ["extremes", [2147483647, -2147483648, 2147483647], [[-2147483648, 1], [2147483647, 2]]],
];

for (const [name, items, want] of cases) {
  test(name, () => {
    assert.deepEqual(countItems(items), want);
  });
}
count_items.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-items-of-each-kind/.

export function countItems(items: readonly number[]): [number, number][] {
  // A Map keeps the numbers as numbers. The keys of an object are strings.
  const counts = new Map<number, number>();
  for (const x of items) {
    counts.set(x, (counts.get(x) ?? 0) + 1);
  }
  // Compare the numbers. sort() without a function compares strings.
  return [...counts].sort((p, q) => p[0] - q[0]);
}
count_items.test.ts 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-items-of-each-kind/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { countItems } from "./count_items.ts";

const cases: [string, number[], [number, number][]][] = [
  ["mixed", [3, 1, 3, 2, 1, 3], [[1, 2], [2, 1], [3, 3]]],
  ["same", [5, 5, 5], [[5, 3]]],
  ["empty", [], []],
  ["single", [7], [[7, 1]]],
  ["negative", [-1, 2, -1, 0], [[-1, 2], [0, 1], [2, 1]]],
  ["distinct", [4, 2, 9], [[2, 1], [4, 1], [9, 1]]],
  ["order", [9, 8, 9], [[8, 1], [9, 2]]],
  ["zero", [0, 0], [[0, 2]]],
  ["extremes", [2147483647, -2147483648, 2147483647], [[-2147483648, 1], [2147483647, 2]]],
];

for (const [name, items, want] of cases) {
  test(name, () => {
    assert.deepEqual(countItems(items), want);
  });
}
count_items.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-items-of-each-kind/.

// Package countitems counts the items of each kind in a slice.
package countitems

import "slices"

// CountItems returns one {item, count} pair for each distinct item, in
// ascending order of the item.
func CountItems(items []int) [][2]int {
	counts := make(map[int]int)
	for _, x := range items {
		counts[x]++
	}
	// The order of a range over a map is not specified, so sort the keys.
	keys := make([]int, 0, len(counts))
	for k := range counts {
		keys = append(keys, k)
	}
	slices.Sort(keys)
	out := make([][2]int, 0, len(keys))
	for _, k := range keys {
		out = append(out, [2]int{k, counts[k]})
	}
	return out
}
count_items_test.go 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-items-of-each-kind/.

package countitems

import (
	"slices"
	"testing"
)

var cases = []struct {
	name  string
	items []int
	want  [][2]int
}{
	{"mixed", []int{3, 1, 3, 2, 1, 3}, [][2]int{{1, 2}, {2, 1}, {3, 3}}},
	{"same", []int{5, 5, 5}, [][2]int{{5, 3}}},
	{"empty", []int{}, [][2]int{}},
	{"single", []int{7}, [][2]int{{7, 1}}},
	{"negative", []int{-1, 2, -1, 0}, [][2]int{{-1, 2}, {0, 1}, {2, 1}}},
	{"distinct", []int{4, 2, 9}, [][2]int{{2, 1}, {4, 1}, {9, 1}}},
	{"order", []int{9, 8, 9}, [][2]int{{8, 1}, {9, 2}}},
	{"zero", []int{0, 0}, [][2]int{{0, 2}}},
	{"extremes", []int{2147483647, -2147483648, 2147483647}, [][2]int{{-2147483648, 1}, {2147483647, 2}}},
}

func TestCountItems(t *testing.T) {
	for _, c := range cases {
		if got := CountItems(c.items); !slices.Equal(got, c.want) {
			t.Errorf("%s: got %v, want %v", c.name, got, c.want)
		}
	}
}
count_items.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-items-of-each-kind/.

use std::collections::BTreeMap;

/// Returns one (item, count) pair for each distinct item, in ascending order of the item.
pub fn count_items(items: &[i32]) -> Vec<(i32, usize)> {
    // A BTreeMap gives its keys in ascending order.
    let mut counts = BTreeMap::new();
    for &x in items {
        *counts.entry(x).or_insert(0) += 1;
    }
    counts.into_iter().collect()
}
tests/count_items_test.rs 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-items-of-each-kind/.

use algo_count_the_items_of_each_kind::count_items;

#[test]
fn cases() {
    let cases: Vec<(&str, &[i32], Vec<(i32, usize)>)> = vec![
        ("mixed", &[3, 1, 3, 2, 1, 3], vec![(1, 2), (2, 1), (3, 3)]),
        ("same", &[5, 5, 5], vec![(5, 3)]),
        ("empty", &[], vec![]),
        ("single", &[7], vec![(7, 1)]),
        ("negative", &[-1, 2, -1, 0], vec![(-1, 2), (0, 1), (2, 1)]),
        ("distinct", &[4, 2, 9], vec![(2, 1), (4, 1), (9, 1)]),
        ("order", &[9, 8, 9], vec![(8, 1), (9, 2)]),
        ("zero", &[0, 0], vec![(0, 2)]),
        ("extremes", &[2147483647, -2147483648, 2147483647], vec![(-2147483648, 1), (2147483647, 2)]),
    ];
    for (name, items, want) in cases {
        assert_eq!(count_items(items), want, "{name}");
    }
}
count_items.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/count-the-items-of-each-kind/.

# count_items ITEM...
# Prints one line "ITEM COUNT" for each distinct item, in ascending order of
# the item. It prints nothing if there are no items.
count_items() {
  # -A makes an associative array. Without it, a key such as -1 is an index
  # that counts back from the end of the array.
  local -A counts=()
  local x
  for x in "$@"; do
    counts[$x]=$((${counts[$x]:-0} + 1))
  done
  # The order of the keys of an associative array is not specified.
  for x in "${!counts[@]}"; do
    printf '%s %s\n' "$x" "${counts[$x]}"
  done | sort -n
}
test_count_items.bats 29 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/count-the-items-of-each-kind/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/count_items.sh"
}

check() { # check WANT GIVEN...
  local want got
  # %b turns each \n in WANT into a newline. The x keeps the trailing
  # newlines, which $(...) removes.
  want=$(printf '%b' "$1"; printf x)
  shift
  got=$(count_items "$@"; printf x)
  [ "$got" = "$want" ] || { printf 'got:  %q\nwant: %q\n' "$got" "$want"; return 1; }
}

@test "mixed" { check "1 2\n2 1\n3 3\n" 3 1 3 2 1 3; }
@test "same" { check "5 3\n" 5 5 5; }
@test "empty" { check ""; }
@test "single" { check "7 1\n" 7; }
@test "negative" { check "-1 2\n0 1\n2 1\n" -1 2 -1 0; }
@test "distinct" { check "2 1\n4 1\n9 1\n" 4 2 9; }
@test "order" { check "8 1\n9 2\n" 9 8 9; }
@test "zero" { check "0 2\n" 0 0; }
@test "extremes" { check "-2147483648 1\n2147483647 2\n" 2147483647 -2147483648 2147483647; }

References

  1. The Python Standard Library, collections, Counter objects
  2. MDN Web Docs, for...in, Description
  3. Java SE 25 API, Interface Map, get(Object)
  4. .NET API reference, Dictionary<TKey,TValue>.Item[TKey] property, Exceptions
  5. The Go Programming Language Specification, Map types
  6. Rust standard library, struct HashMap, keys
  7. cppreference.com, qsort, qsort_s (C), Description
  8. cppreference.com, std::map::operator[], Description
  9. Bash Reference Manual, 6.7 Arrays

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source