mirror of
https://github.com/nim-lang/Nim.git
synced 2026-04-06 07:38:24 +00:00
Add minmax to comparisons (#21820)
* Add `minmax` to sequtils This adds a `minmax` proc to complement `min` and `max`; it computes both results in a single pass for efficiency. * Update lib/pure/collections/sequtils.nim * Add minmax note to changelog. --------- Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
This commit is contained in:
@@ -305,6 +305,7 @@
|
||||
- Added `openArray[char]` overloads for `std/unicode` allowing more code reuse.
|
||||
- Added `safe` parameter to `base64.encodeMime`.
|
||||
- Added `parseutils.parseSize` - inverse to `strutils.formatSize` - to parse human readable sizes.
|
||||
- Added `minmax` to `sequtils`, as a more efficient `(min(_), max(_))` over sequences.
|
||||
|
||||
[//]: # "Deprecations:"
|
||||
- Deprecated `selfExe` for Nimscript.
|
||||
|
||||
@@ -248,6 +248,15 @@ func maxIndex*[T](s: openArray[T]): int {.since: (1, 1).} =
|
||||
for i in 1..high(s):
|
||||
if s[i] > s[result]: result = i
|
||||
|
||||
func minmax*[T](x: openArray[T]): (T, T) =
|
||||
## The minimum and maximum values of `x`. `T` needs to have a `<` operator.
|
||||
var l = x[0]
|
||||
var h = x[0]
|
||||
for i in 1..high(x):
|
||||
if x[i] < l: l = x[i]
|
||||
if h < x[i]: h = x[i]
|
||||
result = (l, h)
|
||||
|
||||
|
||||
template zipImpl(s1, s2, retType: untyped): untyped =
|
||||
proc zip*[S, T](s1: openArray[S], s2: openArray[T]): retType =
|
||||
|
||||
@@ -12,6 +12,7 @@ FilterIt: [1, 3, 7]
|
||||
Concat: [1, 3, 5, 7, 2, 4, 6]
|
||||
Deduplicate: [1, 2, 3, 4, 5, 7]
|
||||
@[()]
|
||||
Minmax: (1, 7)
|
||||
2345623456
|
||||
'''
|
||||
"""
|
||||
@@ -156,6 +157,13 @@ block tsequtils:
|
||||
let someObjSeq = aSeq.mapIt(it.field)
|
||||
echo someObjSeq
|
||||
|
||||
block minmax:
|
||||
doAssert minmax(@[0]) == (0, 0)
|
||||
doAssert minmax(@[0, 1]) == (0, 1)
|
||||
doAssert minmax(@[1, 0]) == (0, 1)
|
||||
doAssert minmax(@[8,2,1,7,3,9,4,0,5]) == (0, 9)
|
||||
echo "Minmax: ", $(minmax(concat(seq1, seq2)))
|
||||
|
||||
|
||||
when not defined(nimseqsv2):
|
||||
block tshallowseq:
|
||||
|
||||
Reference in New Issue
Block a user