Skip to content

Commit 8dc291d

Browse files
committed
Refactor AbsoluteMin.getMinValue for improved
efficiency and readability
1 parent 2830913 commit 8dc291d

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,34 @@
1-
package com.thealgorithms.maths;
2-
3-
import java.util.Arrays;
4-
51
public final class AbsoluteMin {
6-
private AbsoluteMin() {
7-
}
2+
private AbsoluteMin() {}
83

94
/**
105
* Compares the numbers given as arguments to get the absolute min value.
116
*
127
* @param numbers The numbers to compare
138
* @return The absolute min value
9+
* @throws IllegalArgumentException If the input array is empty
1410
*/
1511
public static int getMinValue(int... numbers) {
1612
if (numbers.length == 0) {
1713
throw new IllegalArgumentException("Numbers array cannot be empty");
1814
}
1915

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+
}
2123

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+
}
2330

24-
return absMinWrapper.value;
31+
// This line should never be reached
32+
throw new IllegalStateException("Invalid state");
2533
}
26-
}
34+
}

0 commit comments

Comments
 (0)