File tree 1 file changed +18
-10
lines changed
src/main/java/com/thealgorithms/maths
1 file changed +18
-10
lines changed Original file line number Diff line number Diff line change 1
- package com .thealgorithms .maths ;
2
-
3
- import java .util .Arrays ;
4
-
5
1
public final class AbsoluteMin {
6
- private AbsoluteMin () {
7
- }
2
+ private AbsoluteMin () {}
8
3
9
4
/**
10
5
* Compares the numbers given as arguments to get the absolute min value.
11
6
*
12
7
* @param numbers The numbers to compare
13
8
* @return The absolute min value
9
+ * @throws IllegalArgumentException If the input array is empty
14
10
*/
15
11
public static int getMinValue (int ... numbers ) {
16
12
if (numbers .length == 0 ) {
17
13
throw new IllegalArgumentException ("Numbers array cannot be empty" );
18
14
}
19
15
20
- var absMinWrapper = new Object () { int value = numbers [0 ]; };
16
+ int min = Math .abs (numbers [0 ]);
17
+ for (int number : numbers ) {
18
+ int absValue = Math .abs (number );
19
+ if (absValue < min ) {
20
+ min = absValue ;
21
+ }
22
+ }
21
23
22
- Arrays .stream (numbers ).skip (1 ).filter (number -> Math .abs (number ) < Math .abs (absMinWrapper .value )).forEach (number -> absMinWrapper .value = number );
24
+ // Determine the sign of the minimum value
25
+ for (int number : numbers ) {
26
+ if (Math .abs (number ) == min ) {
27
+ return number ;
28
+ }
29
+ }
23
30
24
- return absMinWrapper .value ;
31
+ // This line should never be reached
32
+ throw new IllegalStateException ("Invalid state" );
25
33
}
26
- }
34
+ }
You can’t perform that action at this time.
0 commit comments