1
+ # # Absolute value
2
+ {.push raises : [].}
3
+ import std/ algorithm
4
+
5
+ runnableExamples:
6
+ doAssert absVal (- 5.1 ) == 5.1
7
+ doAssert absMin (@ [- 1 , 2 , - 3 ]) == 1
8
+ doAssert absMax (@ [- 1 , 2 , - 3 ]) == 3
9
+ doAssert absMaxSort (@ [3 , - 10 , - 2 ]) == - 10
10
+
11
+ func absVal (num: float ): float =
12
+ # # Returns the absolute value of a number.
13
+ return if num < 0.0 : - num else : num
14
+
15
+ # Same for integers but return a Natural
16
+ func absVal (num: int ): Natural = (if num < 0 : - num else : num)
17
+
18
+ func absMin (x: seq [int ]): Natural {.raises : [ValueError ].} =
19
+ # # Returns the smallest element in absolute value in a sequence.
20
+ if x.len == 0 :
21
+ raise newException (ValueError , " Cannot find absolute minimum of an empty sequence" )
22
+ result = absVal (x[0 ])
23
+ for i in 1 ..< x.len:
24
+ if absVal (x[i]) < result :
25
+ result = absVal (x[i])
26
+
27
+ func absMax (x: seq [int ]): Natural {.raises : [ValueError ].} =
28
+ # # Returns the largest element in absolute value in a sequence.
29
+ if x.len == 0 :
30
+ raise newException (ValueError , " Cannot find absolute maximum of an empty sequence" )
31
+ result = absVal (x[0 ])
32
+ for i in 1 ..< x.len:
33
+ if absVal (x[i]) > result :
34
+ result = absVal (x[i])
35
+
36
+ func absMaxSort (x: seq [int ]): int {.raises : [ValueError ].} =
37
+ # # Returns the signed element whose absolute value is the largest in a sequence.
38
+ var x: seq [int ] = x
39
+ if x.len == 0 :
40
+ raise newException (ValueError , " Cannot find absolute maximum of an empty sequence" )
41
+ sort (x, proc (a, b: int ): int = int (absVal (b)) - int (absVal (a)))
42
+ return x[0 ]
43
+
44
+ when isMainModule :
45
+ import std/ [unittest, random]
46
+ randomize ()
47
+
48
+ suite " Check `absVal`" :
49
+ test " Check `absVal`" :
50
+ check:
51
+ absVal (11.2 ) == 11.2
52
+ absVal (5 ) == 5
53
+ absVal (- 5.1 ) == 5.1
54
+ absVal (- 5 ) == abs_val (5 )
55
+ absVal (0 ) == 0
56
+
57
+ suite " Check `absMin`" :
58
+ test " Check `absMin`" :
59
+ check:
60
+ absMin (@ [- 1 , 2 , - 3 ]) == 1
61
+ absMin (@ [0 , 5 , 1 , 11 ]) == 0
62
+ absMin (@ [3 , - 10 , - 2 ]) == 2
63
+
64
+ test " `absMin` on empty sequence raises ValueError" :
65
+ doAssertRaises (ValueError ):
66
+ discard absMin (@ [])
67
+
68
+ suite " Check `absMax`" :
69
+ test " Check `absMax`" :
70
+ check:
71
+ absMax (@ [0 , 5 , 1 , 11 ]) == 11
72
+ absMax (@ [3 , - 10 , - 2 ]) == 10
73
+ absMax (@ [- 1 , 2 , - 3 ]) == 3
74
+
75
+ test " `absMax` on empty sequence raises ValueError" :
76
+ doAssertRaises (ValueError ):
77
+ discard absMax (@ [])
78
+
79
+ suite " Check `absMaxSort`" :
80
+ test " Check `absMaxSort`" :
81
+ check:
82
+ absMaxSort (@ [3 , - 2 , 1 , - 4 , 5 , - 6 ]) == - 6
83
+ absMaxSort (@ [0 , 5 , 1 , 11 ]) == 11
84
+
85
+ test " `absMaxSort` on empty sequence raises ValueError" :
86
+ doAssertRaises (ValueError ):
87
+ discard absMaxSort (@ [])
0 commit comments