summary refs log tree commit diff stats
path: root/lib/pure/collections/sequtils.nim
diff options
context:
space:
mode:
authorMiran <narimiran@disroot.org>2020-01-20 16:57:34 +0100
committerAndreas Rumpf <rumpf_a@web.de>2020-01-20 16:57:34 +0100
commitbf96d6d316b4efdb219633947f05b45a5a76620b (patch)
tree89238941528e6f04a85d89778d8a7df424f88f4d /lib/pure/collections/sequtils.nim
parent0606b6a44e2778697869ed33bff000a1548f36aa (diff)
downloadNim-bf96d6d316b4efdb219633947f05b45a5a76620b.tar.gz
Idxmin & idxmax, continuation (#13208)
* Add idxmin() which returns the index of the minimum value

* Add idxmax() which returns the index of the maximum value

* Add tests for idxmin()

* Add tests for idxmax()

* Remove initialization of result = 0

* Adds overloading for arrays (no enums indexed arrays yet)

* Add support for enum index arrays

* Fix tests with enum

* Fix tests for idxmax

* Change names of the procedures to minIndex and maxIndex

* address Araq's comments:

- remove 'array' versions
- add .since pragma
- return 'int' instead of 'Natural'
- add changelog entry

Co-authored-by: Federico A. Corazza <20555025+Imperator26@users.noreply.github.com>
Diffstat (limited to 'lib/pure/collections/sequtils.nim')
-rw-r--r--lib/pure/collections/sequtils.nim35
1 files changed, 35 insertions, 0 deletions
diff --git a/lib/pure/collections/sequtils.nim b/lib/pure/collections/sequtils.nim
index a20f0d0b7..d56742ba9 100644
--- a/lib/pure/collections/sequtils.nim
+++ b/lib/pure/collections/sequtils.nim
@@ -202,6 +202,41 @@ proc deduplicate*[T](s: openArray[T], isSorted: bool = false): seq[T] =
       for itm in items(s):
         if not result.contains(itm): result.add(itm)
 
+proc minIndex*[T](s: openArray[T]): int {.since: (1, 1).} =
+  ## Returns the index of the minimum value of `s`.
+  ## ``T`` needs to have a ``<`` operator.
+  runnableExamples:
+    let
+      a = @[1, 2, 3, 4]
+      b = @[6, 5, 4, 3]
+      c = [2, -7, 8, -5]
+      d = "ziggy"
+    assert minIndex(a) == 0
+    assert minIndex(b) == 3
+    assert minIndex(c) == 1
+    assert minIndex(d) == 2
+
+  for i in 1..high(s):
+    if s[i] < s[result]: result = i
+
+proc maxIndex*[T](s: openArray[T]): int {.since: (1, 1).} =
+  ## Returns the index of the maximum value of `s`.
+  ## ``T`` needs to have a ``<`` operator.
+  runnableExamples:
+    let
+      a = @[1, 2, 3, 4]
+      b = @[6, 5, 4, 3]
+      c = [2, -7, 8, -5]
+      d = "ziggy"
+    assert maxIndex(a) == 3
+    assert maxIndex(b) == 0
+    assert maxIndex(c) == 2
+    assert maxIndex(d) == 0
+
+  for i in 1..high(s):
+    if s[i] > s[result]: result = i
+
+
 template zipImpl(s1, s2, retType: untyped): untyped =
   proc zip*[S, T](s1: openArray[S], s2: openArray[T]): retType =
     ## Returns a new sequence with a combination of the two input containers.