Programming Search⌘K

Taskintro

Group items by a key

Also called group by, group a list by a key, bucket items by a key, groupBy, group words by length.

Group a list of words by their length, with the groups in ascending order of the length and the words of each group in input order.

Task

Group a list of words by their length. The function group_by_length(words) returns one pair (length, words) for each length that occurs. The pairs are in ascending order of the length. The words of a pair are in input order. For example, group_by_length(["apple", "fig", "kiwi", "pear"]) is [(3, ["fig"]), (4, ["kiwi", "pear"]), (5, ["apple"])].

Each word has 1 or more ASCII letters, so its length is the same in bytes, code units and code points. The list can be empty. Then the result is an empty list.

Solutions

Language Group by the length
Python a defaultdict(list), then sorted of its items
JavaScript, TypeScript Map.groupBy, then a sort with a number comparison
Java Collectors.groupingBy into a TreeMap
C# GroupBy, then OrderBy of the key
Go a map[int][]string, then a loop over the sorted keys
Rust a BTreeMap with entry(..).or_default().push(..)
C a stable insertion sort by the length, then one group for each run of equal lengths
C++ a std::map<std::size_t, std::vector<std::string>>
Bash an associative array of strings, then sort -n
  • The key. Each solution calculates the length of a word once for each word, and uses it as the key of a map. A defaultdict gives an empty list for a new key: "If default_factory is not None, it is called without arguments to provide a default value for the given key"1.
  • The order of the groups. A map of the language gives the keys in key order, or the solution sorts the keys. A TreeMap, a BTreeMap and a std::map keep the keys in order. A BTreeMap "stores its entries in key order"2, and std::map "is a sorted associative container"3.
  • The order of the words. Each solution adds the words to their group in input order. For GroupBy, "Elements in a grouping are yielded in the order that the elements that produced them appear in source."4
  • C. The function writes the words to sorted in ascending order of the length. Each group is a start index and a count in sorted, so the function does not copy the words.
  • Bash. The function prints one line for each group: the length, then the words, separated by spaces. ${#w} "Substitutes the length in characters of the value of parameter"5.

Edge cases

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

  • empty: an empty list gives no groups.
  • single: one word gives one group with that word.
  • same-length: ["cat", "dog", "cow"] gives one group, with the words in input order.
  • order: ["ccc", "a", "bb"] gives the groups 1, 2 and 3, not the order of the first word of each group.
  • duplicates: ["ab", "ab", "c"] keeps the two words "ab" in the group 2.
  • long: the lengths 1, 9 and 10 are in ascending order as numbers. As strings, "10" is before "9".

Pitfalls

  • Python itertools.groupby groups only adjacent items. "It generates a break or new group every time the value of the key function changes"6. In the example, the two words of length 1 are in two groups. "Generally, the iterable needs to already be sorted on the same key function."6 A defaultdict keeps the keys in the order of their first word, so sort its items:
from collections import defaultdict
from itertools import groupby

words = ["a", "bb", "c"]
print([(k, list(g)) for k, g in groupby(words, len)])
print([(k, list(g)) for k, g in groupby(sorted(words, key=len), len)])
groups = defaultdict(list)
for w in ["apple", "fig", "kiwi", "pear"]:
    groups[len(w)].append(w)
print(dict(groups))
print(sorted(groups.items()))
Output
[(1, ['a']), (2, ['bb']), (1, ['c'])]
[(1, ['a', 'c']), (2, ['bb'])]
{5: ['apple'], 3: ['fig'], 4: ['kiwi', 'pear']}
[(3, ['fig']), (4, ['kiwi', 'pear']), (5, ['apple'])]
  • JavaScript sort compares strings. Map.groupBy returns "A Map object with keys for each group"7, in the order of the first word of each group. But "The default sort order is ascending, built upon converting the elements into strings"8. In the example, the length 10 is before 9. Give a comparison function:
const words = ["abcdefghij", "a", "abcdefghi"];
const groups = Map.groupBy(words, (w) => w.length);
console.log([...groups].sort().map((p) => p[0]));
console.log([...groups].sort((p, q) => p[0] - q[0]).map((p) => p[0]));
Output
[ 1, 10, 9 ]
[ 1, 9, 10 ]
  • Java groupingBy gives no order of the keys. For groupingBy(classifier), "There are no guarantees on the type, mutability, serializability, or thread-safety of the Map or List objects returned."9 Give TreeMap::new as the map factory, and the keys are in ascending order:
import java.util.List;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class Main {
  public static void main(String[] args) {
    var words = List.of("apple", "fig", "kiwi", "pear", "plum", "date");
    TreeMap<Integer, List<String>> groups = words.stream()
        .collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.toList()));
    System.out.println(groups);
  }
}
Output
{3=[fig], 4=[kiwi, pear, plum, date], 5=[apple]}
  • C# GroupBy gives the groups in the order of their first item. "The IGrouping<TKey,TElement> objects are yielded in an order based on the order of the elements in source that produced the first key of each IGrouping<TKey,TElement>."4 In the example, the first line is 5 3 4. Add OrderBy:
using System;
using System.Linq;

var words = new[] { "apple", "fig", "kiwi", "pear" };
Console.WriteLine(string.Join(" ", words.GroupBy(w => w.Length).Select(g => g.Key)));
Console.WriteLine(string.Join(" ", words.GroupBy(w => w.Length).OrderBy(g => g.Key).Select(g => g.Key)));
Output
5 3 4
3 4 5
  • Go an append to a copy of the slice does not change the map. append "returns the resulting slice"10. In the first loop, g is a copy of the slice in the map, and the map stays empty. Store the result of append in the map. Also, "The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next."10 Thus the solution sorts the keys:
package main

import "fmt"

func main() {
	groups := make(map[int][]string)
	for _, w := range []string{"fig", "kiwi", "pear"} {
		g := groups[len(w)]
		g = append(g, w)
		_ = g
	}
	fmt.Println(groups, len(groups))
	for _, w := range []string{"fig", "kiwi", "pear"} {
		groups[len(w)] = append(groups[len(w)], w)
	}
	fmt.Println(groups, len(groups))
}
Output
map[] 0
map[3:[fig] 4:[kiwi pear]] 2
  • Rust HashMap gives the keys in arbitrary order. keys is "An iterator visiting all keys in arbitrary order."11 Use a BTreeMap, which "stores its entries in key order"2:
use std::collections::BTreeMap;

fn main() {
    let words = ["apple", "fig", "kiwi", "pear"];
    let mut groups: BTreeMap<usize, Vec<&str>> = BTreeMap::new();
    for w in words {
        groups.entry(w.len()).or_default().push(w);
    }
    println!("{groups:?}");
}
Output
{3: ["fig"], 4: ["kiwi", "pear"], 5: ["apple"]}
  • C qsort is not stable. "If comp indicates two elements as equivalent, their order in the resulting sorted array is unspecified."12 Thus qsort by the length can change the order of the words in a group. The solution uses an insertion sort, which moves a word only past longer words:
#include <stdio.h>
#include <string.h>

struct word_group {
    size_t len;
    size_t start;
    size_t count;
};

static size_t group_by_length(const char *const *words, size_t n, const char **sorted, struct word_group *out) {
    // An insertion sort is stable: it moves a word only past longer words.
    // qsort does not keep the order of equal items.
    for (size_t i = 0; i < n; i++) {
        size_t j = i;
        size_t len = strlen(words[i]);
        while (j > 0 && strlen(sorted[j - 1]) > len) {
            sorted[j] = sorted[j - 1];
            j--;
        }
        sorted[j] = words[i];
    }
    size_t k = 0;
    for (size_t i = 0; i < n; i++) {
        size_t len = strlen(sorted[i]);
        if (k > 0 && out[k - 1].len == len) {
            out[k - 1].count++;
        } else {
            out[k].len = len;
            out[k].start = i;
            out[k].count = 1;
            k++;
        }
    }
    return k;
}

int main(void) {
    const char *words[] = {"apple", "fig", "kiwi", "pear"};
    const char *sorted[4];
    struct word_group g[4];
    size_t k = group_by_length(words, 4, sorted, g);
    for (size_t i = 0; i < k; i++) {
        printf("%zu:", g[i].len);
        for (size_t j = g[i].start; j < g[i].start + g[i].count; j++) {
            printf(" %s", sorted[j]);
        }
        printf("\n");
    }
    return 0;
}
Output
3: fig
4: kiwi pear
5: apple
  • C++ std::map sorts the keys. "Keys are sorted by using the comparison function Compare."3 A loop over the map gives the groups in ascending order of the length:
#include <iostream>
#include <map>
#include <string>
#include <vector>

int main() {
    std::map<std::size_t, std::vector<std::string>> groups;
    for (std::string w : {"apple", "fig", "kiwi", "pear"}) {
        groups[w.size()].push_back(w);
    }
    for (const auto &[len, ws] : groups) {
        std::cout << len << ':';
        for (const auto &w : ws) {
            std::cout << ' ' << w;
        }
        std::cout << '\n';
    }
}
Output
3: fig
4: kiwi pear
5: apple
  • Bash an associative array needs declare -A. "Associative arrays are created using declare -A name"5. In a function, local -A makes a local associative array, because for local, "The option can be any of the options accepted by declare."5 Then += adds to the string of a key: "When applied to a string-valued variable, value is expanded and appended to the variable’s value."5 The last line of the example is ${#w} for abc:
group_by_length() {
  local -A groups=()
  local w
  for w in "$@"; do
    groups[${#w}]+=" $w"
  done
  # sort -n puts the lines in ascending order of the length.
  for w in "${!groups[@]}"; do
    printf '%s%s\n' "$w" "${groups[$w]}"
  done | sort -n
}
group_by_length apple fig kiwi pear plum date
w=abc; echo "${#w}"
Output
3 fig
4 kiwi pear plum date
5 apple
3

Code

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

group_by_length.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/group-items-by-a-key/.

from collections import defaultdict


def group_by_length(words: list[str]) -> list[tuple[int, list[str]]]:
    """Return one (length, words) pair for each length, in ascending order of the length."""
    groups: defaultdict[int, list[str]] = defaultdict(list)
    for word in words:
        groups[len(word)].append(word)
    return sorted(groups.items())
test_group_by_length.py 23 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/group-items-by-a-key/.

import pytest

from group_by_length import group_by_length

CASES = {
    "fruits": (["apple", "fig", "kiwi", "pear", "plum", "date"], [(3, ["fig"]), (4, ["kiwi", "pear", "plum", "date"]), (5, ["apple"])]),
    "letters": (["a", "bb", "c"], [(1, ["a", "c"]), (2, ["bb"])]),
    "empty": ([], []),
    "single": (["x"], [(1, ["x"])]),
    "same-length": (["cat", "dog", "cow"], [(3, ["cat", "dog", "cow"])]),
    "order": (["ccc", "a", "bb"], [(1, ["a"]), (2, ["bb"]), (3, ["ccc"])]),
    "duplicates": (["ab", "ab", "c"], [(1, ["c"]), (2, ["ab", "ab"])]),
    "long": (["abcdefghij", "abcdefghi", "a"], [(1, ["a"]), (9, ["abcdefghi"]), (10, ["abcdefghij"])]),
}


@pytest.mark.parametrize("name", CASES)
def test_group_by_length(name):
    words, want = CASES[name]
    assert group_by_length(words) == want
group_by_length.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/group-items-by-a-key/.

#include "group_by_length.hpp"

#include <map>

std::vector<std::pair<std::size_t, std::vector<std::string>>> group_by_length(const std::vector<std::string> &words) {
    // A std::map keeps its keys in ascending order.
    std::map<std::size_t, std::vector<std::string>> groups;
    for (const auto &w : words) {
        groups[w.size()].push_back(w);
    }
    return {groups.begin(), groups.end()};
}
group_by_length.hpp 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/group-items-by-a-key/.

#pragma once

#include <cstddef>
#include <string>
#include <utility>
#include <vector>

// group_by_length returns one (length, words) pair for each length, in
// ascending order of the length. The words of a pair are in input order.
std::vector<std::pair<std::size_t, std::vector<std::string>>> group_by_length(const std::vector<std::string> &words);
test_group_by_length.cpp 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/group-items-by-a-key/.

#include "group_by_length.hpp"

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

static int failures = 0;

using Groups = std::vector<std::pair<std::size_t, std::vector<std::string>>>;

static void check(std::string_view name, const std::vector<std::string> &words, const Groups &want) {
    if (group_by_length(words) != want) {
        std::cerr << "case " << name << " failed\n";
        failures++;
    }
}

int main() {
    check("fruits", std::vector<std::string>{"apple", "fig", "kiwi", "pear", "plum", "date"}, Groups{{3, {"fig"}}, {4, {"kiwi", "pear", "plum", "date"}}, {5, {"apple"}}});
    check("letters", std::vector<std::string>{"a", "bb", "c"}, Groups{{1, {"a", "c"}}, {2, {"bb"}}});
    check("empty", std::vector<std::string>{}, Groups{});
    check("single", std::vector<std::string>{"x"}, Groups{{1, {"x"}}});
    check("same-length", std::vector<std::string>{"cat", "dog", "cow"}, Groups{{3, {"cat", "dog", "cow"}}});
    check("order", std::vector<std::string>{"ccc", "a", "bb"}, Groups{{1, {"a"}}, {2, {"bb"}}, {3, {"ccc"}}});
    check("duplicates", std::vector<std::string>{"ab", "ab", "c"}, Groups{{1, {"c"}}, {2, {"ab", "ab"}}});
    check("long", std::vector<std::string>{"abcdefghij", "abcdefghi", "a"}, Groups{{1, {"a"}}, {9, {"abcdefghi"}}, {10, {"abcdefghij"}}});
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
GroupByLength.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/group-items-by-a-key/.

import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.stream.Collectors;

final class GroupByLength {
  private GroupByLength() {}

  /** Returns the words of each length, in ascending order of the length. */
  static SortedMap<Integer, List<String>> groupByLength(List<String> words) {
    // A TreeMap keeps the keys in order. toList keeps the order of the words.
    return words.stream()
        .collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.toList()));
  }
}
GroupByLengthTest.java 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/group-items-by-a-key/.

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

import java.util.List;
import java.util.Map;
import java.util.TreeMap;
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 GroupByLengthTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("fruits", List.of("apple", "fig", "kiwi", "pear", "plum", "date"), Map.of(3, List.of("fig"), 4, List.of("kiwi", "pear", "plum", "date"), 5, List.of("apple"))),
        Arguments.of("letters", List.of("a", "bb", "c"), Map.of(1, List.of("a", "c"), 2, List.of("bb"))),
        Arguments.of("empty", List.of(), Map.of()),
        Arguments.of("single", List.of("x"), Map.of(1, List.of("x"))),
        Arguments.of("same-length", List.of("cat", "dog", "cow"), Map.of(3, List.of("cat", "dog", "cow"))),
        Arguments.of("order", List.of("ccc", "a", "bb"), Map.of(1, List.of("a"), 2, List.of("bb"), 3, List.of("ccc"))),
        Arguments.of("duplicates", List.of("ab", "ab", "c"), Map.of(1, List.of("c"), 2, List.of("ab", "ab"))),
        Arguments.of("long", List.of("abcdefghij", "abcdefghi", "a"), Map.of(1, List.of("a"), 9, List.of("abcdefghi"), 10, List.of("abcdefghij"))));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void groupByLength(String name, List<String> words, Map<Integer, List<String>> want) {
    var got = GroupByLength.groupByLength(words);
    assertEquals(new TreeMap<>(want), got);
    // The keys of the result are in ascending order.
    assertEquals(List.copyOf(new TreeMap<>(want).keySet()), List.copyOf(got.keySet()));
  }
}
group_by_length.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/group-items-by-a-key/.

#include "group_by_length.h"

#include <string.h>

size_t group_by_length(const char *const *words, size_t n, const char **sorted, struct word_group *out) {
    // An insertion sort is stable: it moves a word only past longer words.
    // qsort does not keep the order of equal items.
    for (size_t i = 0; i < n; i++) {
        size_t j = i;
        size_t len = strlen(words[i]);
        while (j > 0 && strlen(sorted[j - 1]) > len) {
            sorted[j] = sorted[j - 1];
            j--;
        }
        sorted[j] = words[i];
    }
    size_t k = 0;
    for (size_t i = 0; i < n; i++) {
        size_t len = strlen(sorted[i]);
        if (k > 0 && out[k - 1].len == len) {
            out[k - 1].count++;
        } else {
            out[k].len = len;
            out[k].start = i;
            out[k].count = 1;
            k++;
        }
    }
    return k;
}
group_by_length.h 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/group-items-by-a-key/.

#ifndef GROUP_BY_LENGTH_H
#define GROUP_BY_LENGTH_H

#include <stddef.h>

// A group is sorted[start .. start + count), the words with the length len.
struct word_group {
    size_t len;
    size_t start;
    size_t count;
};

// group_by_length writes the n words to sorted in ascending order of the
// length, and keeps the input order of words with the same length. It writes
// one group for each length to out, and returns the number of groups. sorted
// and out must each have room for n items.
size_t group_by_length(const char *const *words, size_t n, const char **sorted, struct word_group *out);

#endif
test_group_by_length.c 53 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/group-items-by-a-key/.

#include "group_by_length.h"

#include <stdio.h>
#include <string.h>

static int failures = 0;

#define L(...) {__VA_ARGS__}

// An empty list has "" in it, because C has no empty array. The counts give the
// real lengths. ORDER is the words in the order of sorted.
#define CHECK(name, n, given, order, m, ...)                                   \
    do {                                                                       \
        const char *const g[] = given;                                         \
        const char *const o[] = order;                                         \
        const struct word_group w[] = {__VA_ARGS__};                           \
        const char *sorted[sizeof g / sizeof g[0]];                            \
        struct word_group out[sizeof g / sizeof g[0]];                         \
        const size_t want_n = m;                                               \
        const size_t have_n = n;                                               \
        size_t k = group_by_length(g, have_n, sorted, out);                    \
        int ok = k == want_n;                                                  \
        for (size_t i = 0; ok && i < have_n; i++) {                            \
            ok = strcmp(sorted[i], o[i]) == 0;                                 \
        }                                                                      \
        for (size_t i = 0; ok && i < want_n; i++) {                            \
            ok = out[i].len == w[i].len && out[i].start == w[i].start &&       \
                 out[i].count == w[i].count;                                   \
        }                                                                      \
        if (!ok) {                                                             \
            fprintf(stderr, "case %s failed\n", name);                         \
            failures++;                                                        \
        }                                                                      \
    } while (0)

int main(void) {
    CHECK("fruits", 6, L("apple", "fig", "kiwi", "pear", "plum", "date"), L("fig", "kiwi", "pear", "plum", "date", "apple"), 3, {3, 0, 1}, {4, 1, 4}, {5, 5, 1});
    CHECK("letters", 3, L("a", "bb", "c"), L("a", "c", "bb"), 2, {1, 0, 2}, {2, 2, 1});
    CHECK("empty", 0, L(""), L(""), 0, {0, 0, 0});
    CHECK("single", 1, L("x"), L("x"), 1, {1, 0, 1});
    CHECK("same-length", 3, L("cat", "dog", "cow"), L("cat", "dog", "cow"), 1, {3, 0, 3});
    CHECK("order", 3, L("ccc", "a", "bb"), L("a", "bb", "ccc"), 3, {1, 0, 1}, {2, 1, 1}, {3, 2, 1});
    CHECK("duplicates", 3, L("ab", "ab", "c"), L("c", "ab", "ab"), 2, {1, 0, 1}, {2, 1, 2});
    CHECK("long", 3, L("abcdefghij", "abcdefghi", "a"), L("a", "abcdefghi", "abcdefghij"), 3, {1, 0, 1}, {9, 1, 1}, {10, 2, 1});
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
GroupByLength.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/group-items-by-a-key/.

using System.Linq;

public static class GroupByLength
{
    // Group returns one (length, words) pair for each length, in ascending order of the length.
    public static (int Length, string[] Words)[] Group(string[] words)
    {
        return words
            .GroupBy(w => w.Length)
            .OrderBy(g => g.Key)
            .Select(g => (g.Key, g.ToArray()))
            .ToArray();
    }
}
GroupByLengthTests.cs 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/group-items-by-a-key/.

using System.Linq;
using Xunit;

public sealed class GroupByLengthTests
{
    public static TheoryData<string, string[], int[], string[][]> Cases => new()
    {
        { "fruits", new string[] { "apple", "fig", "kiwi", "pear", "plum", "date" }, new[] { 3, 4, 5 }, new string[][] { new[] { "fig" }, new[] { "kiwi", "pear", "plum", "date" }, new[] { "apple" } } },
        { "letters", new string[] { "a", "bb", "c" }, new[] { 1, 2 }, new string[][] { new[] { "a", "c" }, new[] { "bb" } } },
        { "empty", new string[0], new int[0], new string[0][] },
        { "single", new string[] { "x" }, new[] { 1 }, new string[][] { new[] { "x" } } },
        { "same-length", new string[] { "cat", "dog", "cow" }, new[] { 3 }, new string[][] { new[] { "cat", "dog", "cow" } } },
        { "order", new string[] { "ccc", "a", "bb" }, new[] { 1, 2, 3 }, new string[][] { new[] { "a" }, new[] { "bb" }, new[] { "ccc" } } },
        { "duplicates", new string[] { "ab", "ab", "c" }, new[] { 1, 2 }, new string[][] { new[] { "c" }, new[] { "ab", "ab" } } },
        { "long", new string[] { "abcdefghij", "abcdefghi", "a" }, new[] { 1, 9, 10 }, new string[][] { new[] { "a" }, new[] { "abcdefghi" }, new[] { "abcdefghij" } } },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, string[] words, int[] lengths, string[][] groups)
    {
        Assert.NotNull(name);
        var got = GroupByLength.Group(words);
        Assert.Equal(lengths, got.Select(g => g.Length));
        Assert.Equal(groups, got.Select(g => g.Words));
    }
}
group_by_length.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/group-items-by-a-key/.

/**
 * @param {string[]} words
 * @returns {[number, string[]][]}
 */
export function groupByLength(words) {
  // Map.groupBy keeps the keys in the order of their first word.
  const groups = Map.groupBy(words, (word) => word.length);
  // Compare the lengths as numbers. sort() without a function compares strings.
  return [...groups].sort((p, q) => p[0] - q[0]);
}
group_by_length.test.js 24 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/group-items-by-a-key/.

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

import { groupByLength } from "./group_by_length.js";

const cases = [
  ["fruits", ["apple", "fig", "kiwi", "pear", "plum", "date"], [[3, ["fig"]], [4, ["kiwi", "pear", "plum", "date"]], [5, ["apple"]]]],
  ["letters", ["a", "bb", "c"], [[1, ["a", "c"]], [2, ["bb"]]]],
  ["empty", [], []],
  ["single", ["x"], [[1, ["x"]]]],
  ["same-length", ["cat", "dog", "cow"], [[3, ["cat", "dog", "cow"]]]],
  ["order", ["ccc", "a", "bb"], [[1, ["a"]], [2, ["bb"]], [3, ["ccc"]]]],
  ["duplicates", ["ab", "ab", "c"], [[1, ["c"]], [2, ["ab", "ab"]]]],
  ["long", ["abcdefghij", "abcdefghi", "a"], [[1, ["a"]], [9, ["abcdefghi"]], [10, ["abcdefghij"]]]],
];

for (const [name, words, want] of cases) {
  test(name, () => {
    assert.deepEqual(groupByLength(words), want);
  });
}
group_by_length.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/group-items-by-a-key/.

export function groupByLength(words: readonly string[]): [number, string[]][] {
  // Map.groupBy keeps the keys in the order of their first word.
  const groups = Map.groupBy(words, (word) => word.length);
  // Compare the lengths as numbers. sort() without a function compares strings.
  return [...groups].sort((p, q) => p[0] - q[0]);
}
group_by_length.test.ts 24 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/group-items-by-a-key/.

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

import { groupByLength } from "./group_by_length.ts";

const cases: [string, string[], [number, string[]][]][] = [
  ["fruits", ["apple", "fig", "kiwi", "pear", "plum", "date"], [[3, ["fig"]], [4, ["kiwi", "pear", "plum", "date"]], [5, ["apple"]]]],
  ["letters", ["a", "bb", "c"], [[1, ["a", "c"]], [2, ["bb"]]]],
  ["empty", [], []],
  ["single", ["x"], [[1, ["x"]]]],
  ["same-length", ["cat", "dog", "cow"], [[3, ["cat", "dog", "cow"]]]],
  ["order", ["ccc", "a", "bb"], [[1, ["a"]], [2, ["bb"]], [3, ["ccc"]]]],
  ["duplicates", ["ab", "ab", "c"], [[1, ["c"]], [2, ["ab", "ab"]]]],
  ["long", ["abcdefghij", "abcdefghi", "a"], [[1, ["a"]], [9, ["abcdefghi"]], [10, ["abcdefghij"]]]],
];

for (const [name, words, want] of cases) {
  test(name, () => {
    assert.deepEqual(groupByLength(words), want);
  });
}
group_by_length.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/group-items-by-a-key/.

// Package groupbylength groups words by their length.
package groupbylength

import "slices"

// Group is the words of one length.
type Group struct {
	Len   int
	Words []string
}

// GroupByLength returns one group for each length, in ascending order of the
// length. The words of a group are in input order.
func GroupByLength(words []string) []Group {
	groups := make(map[int][]string)
	for _, w := range words {
		// append can make a new slice, so store the result in the map.
		groups[len(w)] = append(groups[len(w)], w)
	}
	keys := make([]int, 0, len(groups))
	for k := range groups {
		keys = append(keys, k)
	}
	slices.Sort(keys)
	out := make([]Group, 0, len(keys))
	for _, k := range keys {
		out = append(out, Group{k, groups[k]})
	}
	return out
}
group_by_length_test.go 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/group-items-by-a-key/.

package groupbylength

import (
	"slices"
	"testing"
)

var cases = []struct {
	name  string
	words []string
	want  []Group
}{
	{"fruits", []string{"apple", "fig", "kiwi", "pear", "plum", "date"}, []Group{{3, []string{"fig"}}, {4, []string{"kiwi", "pear", "plum", "date"}}, {5, []string{"apple"}}}},
	{"letters", []string{"a", "bb", "c"}, []Group{{1, []string{"a", "c"}}, {2, []string{"bb"}}}},
	{"empty", []string{}, []Group{}},
	{"single", []string{"x"}, []Group{{1, []string{"x"}}}},
	{"same-length", []string{"cat", "dog", "cow"}, []Group{{3, []string{"cat", "dog", "cow"}}}},
	{"order", []string{"ccc", "a", "bb"}, []Group{{1, []string{"a"}}, {2, []string{"bb"}}, {3, []string{"ccc"}}}},
	{"duplicates", []string{"ab", "ab", "c"}, []Group{{1, []string{"c"}}, {2, []string{"ab", "ab"}}}},
	{"long", []string{"abcdefghij", "abcdefghi", "a"}, []Group{{1, []string{"a"}}, {9, []string{"abcdefghi"}}, {10, []string{"abcdefghij"}}}},
}

func same(a, b Group) bool {
	return a.Len == b.Len && slices.Equal(a.Words, b.Words)
}

func TestGroupByLength(t *testing.T) {
	for _, c := range cases {
		if got := GroupByLength(c.words); !slices.EqualFunc(got, c.want, same) {
			t.Errorf("%s: got %v, want %v", c.name, got, c.want)
		}
	}
}
group_by_length.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/group-items-by-a-key/.

use std::collections::BTreeMap;

/// Returns one (length, words) pair for each length, in ascending order of the length.
pub fn group_by_length<'a>(words: &[&'a str]) -> Vec<(usize, Vec<&'a str>)> {
    // A BTreeMap gives its keys in ascending order.
    let mut groups: BTreeMap<usize, Vec<&'a str>> = BTreeMap::new();
    for &w in words {
        groups.entry(w.len()).or_default().push(w);
    }
    groups.into_iter().collect()
}
tests/group_by_length_test.rs 21 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/group-items-by-a-key/.

use algo_group_items_by_a_key::group_by_length;

#[test]
fn cases() {
    let cases: Vec<(&str, &[&str], Vec<(usize, Vec<&str>)>)> = vec![
        ("fruits", &["apple", "fig", "kiwi", "pear", "plum", "date"], vec![(3, vec!["fig"]), (4, vec!["kiwi", "pear", "plum", "date"]), (5, vec!["apple"])]),
        ("letters", &["a", "bb", "c"], vec![(1, vec!["a", "c"]), (2, vec!["bb"])]),
        ("empty", &[], vec![]),
        ("single", &["x"], vec![(1, vec!["x"])]),
        ("same-length", &["cat", "dog", "cow"], vec![(3, vec!["cat", "dog", "cow"])]),
        ("order", &["ccc", "a", "bb"], vec![(1, vec!["a"]), (2, vec!["bb"]), (3, vec!["ccc"])]),
        ("duplicates", &["ab", "ab", "c"], vec![(1, vec!["c"]), (2, vec!["ab", "ab"])]),
        ("long", &["abcdefghij", "abcdefghi", "a"], vec![(1, vec!["a"]), (9, vec!["abcdefghi"]), (10, vec!["abcdefghij"])]),
    ];
    for (name, words, want) in cases {
        assert_eq!(group_by_length(words), want, "{name}");
    }
}
group_by_length.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/group-items-by-a-key/.

# group_by_length WORD...
# Prints one line "LENGTH WORD..." for each length, in ascending order of the
# length. The words of a line are in input order.
group_by_length() {
  local -A groups=()
  local w
  for w in "$@"; do
    groups[${#w}]+=" $w"
  done
  # sort -n puts the lines in ascending order of the length.
  for w in "${!groups[@]}"; do
    printf '%s%s\n' "$w" "${groups[$w]}"
  done | sort -n
}
test_group_by_length.bats 28 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/group-items-by-a-key/.

bats_require_minimum_version 1.5.0

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

check() { # check WANT WORD...
  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=$(group_by_length "$@"; printf x)
  [ "$got" = "$want" ] || { printf 'got:  %q\nwant: %q\n' "$got" "$want"; return 1; }
}

@test "fruits" { check "3 fig\n4 kiwi pear plum date\n5 apple\n" apple fig kiwi pear plum date; }
@test "letters" { check "1 a c\n2 bb\n" a bb c; }
@test "empty" { check ""; }
@test "single" { check "1 x\n" x; }
@test "same-length" { check "3 cat dog cow\n" cat dog cow; }
@test "order" { check "1 a\n2 bb\n3 ccc\n" ccc a bb; }
@test "duplicates" { check "1 c\n2 ab ab\n" ab ab c; }
@test "long" { check "1 a\n9 abcdefghi\n10 abcdefghij\n" abcdefghij abcdefghi a; }

References

  1. The Python Standard Library, collections, defaultdict objects
  2. Rust standard library, struct BTreeMap, Description
  3. cppreference.com, std::map, Description
  4. .NET API reference, Enumerable.GroupBy method, Remarks
  5. Bash Reference Manual, 3.4 Shell Parameters; 3.5.3 Shell Parameter Expansion
  6. The Python Standard Library, itertools, itertools.groupby()
  7. MDN Web Docs, Map.groupBy(), Return value
  8. MDN Web Docs, Array.prototype.sort(), Description
  9. Java SE 25 API, Class Collectors, groupingBy(Function)
  10. The Go Programming Language Specification, For statements with range clause; Appending to and copying slices
  11. Rust standard library, struct HashMap, keys
  12. cppreference.com, qsort (C), Description

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