-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Abs.cs
73 lines (65 loc) · 2.15 KB
/
Abs.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System;
using System.Numerics;
namespace Algorithms.Numeric;
/// <summary>
/// Find the absolute value of a number.
/// </summary>
public static class Abs
{
/// <summary>
/// Returns the absolute value of a number.
/// </summary>
/// <typeparam name="T">Type of number.</typeparam>
/// <param name="inputNum">Number to find the absolute value of.</param>
/// <returns>Absolute value of the number.</returns>
public static T AbsVal<T>(T inputNum) where T : INumber<T>
{
return T.IsNegative(inputNum) ? -inputNum : inputNum;
}
/// <summary>
/// Returns the number with the smallest absolute value on the input array.
/// </summary>
/// <typeparam name="T">Type of number.</typeparam>
/// <param name="inputNums">Array of numbers to find the smallest absolute.</param>
/// <returns>Smallest absolute number.</returns>
public static T AbsMin<T>(T[] inputNums) where T : INumber<T>
{
if (inputNums.Length == 0)
{
throw new ArgumentException("Array is empty.");
}
var min = inputNums[0];
for (var index = 1; index < inputNums.Length; index++)
{
var current = inputNums[index];
if (AbsVal(current).CompareTo(AbsVal(min)) < 0)
{
min = current;
}
}
return min;
}
/// <summary>
/// Returns the number with the largest absolute value on the input array.
/// </summary>
/// <typeparam name="T">Type of number.</typeparam>
/// <param name="inputNums">Array of numbers to find the largest absolute.</param>
/// <returns>Largest absolute number.</returns>
public static T AbsMax<T>(T[] inputNums) where T : INumber<T>
{
if (inputNums.Length == 0)
{
throw new ArgumentException("Array is empty.");
}
var max = inputNums[0];
for (var index = 1; index < inputNums.Length; index++)
{
var current = inputNums[index];
if (AbsVal(current).CompareTo(AbsVal(max)) > 0)
{
max = current;
}
}
return max;
}
}