group

Groups consecutively equivalent elements into a single tuple of the element and the number of its repetitions.

Similarly to uniq, group produces a range that iterates over unique consecutive elements of the given range. Each element of this range is a tuple of the element and the number of times it is repeated in the original range. Equivalence of elements is assessed by using the predicate pred, which defaults to "a == b". The predicate is passed to std.functional.binaryFun, and can either accept a string, or any callable that can be executed via pred(element, element).

  1. Group!(pred, Range) group(Range r)
    Group!(pred, Range)
    group
    (
    alias pred = "a == b"
    Range
    )
    (
    Range r
    )
  2. struct Group(alias pred, R)

Parameters

pred

Binary predicate for determining equivalence of two elements.

r
Type: Range

The input range to iterate over.

Return Value

Type: Group!(pred, Range)

A range of elements of type Tuple!(ElementType!R, uint), representing each consecutively unique element and its respective number of occurrences in that run. This will be an input range if R is an input range, and a forward range in all other cases.

Examples

1 import std.algorithm.comparison : equal;
2 import std.typecons : tuple, Tuple;
3 
4 int[] arr = [ 1, 2, 2, 2, 2, 3, 4, 4, 4, 5 ];
5 assert(equal(group(arr), [ tuple(1, 1u), tuple(2, 4u), tuple(3, 1u),
6     tuple(4, 3u), tuple(5, 1u) ][]));

Using group, an associative array can be easily generated with the count of each unique element in the range.

1 import std.algorithm.sorting : sort;
2 import std.array : assocArray;
3 
4 uint[string] result;
5 auto range = ["a", "b", "a", "c", "b", "c", "c", "d", "e"];
6 result = range.sort!((a, b) => a < b)
7     .group
8     .assocArray;
9 
10 assert(result == ["a": 2U, "b": 2U, "c": 3U, "d": 1U, "e": 1U]);

See Also

chunkBy, which chunks an input range into subranges of equivalent adjacent elements.

Meta