minElement

Iterates the passed range and returns the minimal element. A custom mapping function can be passed to map. In other languages this is sometimes called argmin.

Complexity: O(n) Exactly n - 1 comparisons are needed.

  1. auto minElement(Range r)
    minElement
    (
    alias map = (a => a)
    Range
    )
    (
    Range r
    )
    if (
    isInputRange!Range &&
    !isInfinite!Range
    )
  2. auto minElement(Range r, RangeElementType seed)

Parameters

map

custom accessor for the comparison key

r Range

range from which the minimal element will be selected

Return Value

Type: auto

The minimal element of the passed-in range.

Note: If at least one of the arguments is NaN, the result is an unspecified value.

If you want to ignore NaNs, you can use std.algorithm.iteration.filter and std.math.isNaN to remove them, before applying minElement. Add a suitable seed, to avoid error messages if all elements are NaNs:

<range>.filter!(a=>!a.isNaN).minElement(<seed>);

If you want to get NaN as a result if a NaN is present in the range, you can use std.algorithm.iteration.fold and std.math.isNaN:

<range>.fold!((a,b)=>a.isNaN || b.isNaN ? real.nan : a < b ? a : b);

Examples

import std.range : enumerate;
import std.typecons : tuple;

assert([2, 7, 1, 3].minElement == 1);

// allows to get the index of an element too
assert([5, 3, 7, 9].enumerate.minElement!"a.value" == tuple(1, 3));

// any custom accessor can be passed
assert([[0, 4], [1, 2]].minElement!"a[1]" == [1, 2]);

// can be seeded
int[] arr;
assert(arr.minElement(1) == 1);

See Also

Meta