Skip to content

Commit d160156

Browse files
Update AbsoluteMax (TheAlgorithms#4140)
1 parent ad72c28 commit d160156

File tree

2 files changed

+16
-25
lines changed

2 files changed

+16
-25
lines changed
Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,24 @@
11
package com.thealgorithms.maths;
22

3-
import java.util.Arrays;
4-
53
public class AbsoluteMax {
64

75
/**
8-
* Compares the numbers given as arguments to get the absolute max value.
6+
* Finds the absolute maximum value among the given numbers.
97
*
10-
* @param numbers The numbers to compare
11-
* @return The absolute max value
8+
* @param numbers The numbers to compare.
9+
* @return The absolute maximum value.
10+
* @throws IllegalArgumentException If the input array is empty or null.
1211
*/
1312
public static int getMaxValue(int... numbers) {
14-
if (numbers.length == 0) {
15-
throw new IllegalArgumentException("Numbers array cannot be empty");
13+
if (numbers == null || numbers.length == 0) {
14+
throw new IllegalArgumentException("Numbers array cannot be empty or null");
1615
}
17-
18-
var absMaxWrapper = new Object() {
19-
int value = numbers[0];
20-
};
21-
22-
Arrays
23-
.stream(numbers)
24-
.skip(1)
25-
.filter(number -> Math.abs(number) > Math.abs(absMaxWrapper.value))
26-
.forEach(number -> absMaxWrapper.value = number);
27-
28-
return absMaxWrapper.value;
16+
int absMax = numbers[0];
17+
for (int i = 1; i < numbers.length; i++) {
18+
if (Math.abs(numbers[i]) > Math.abs(absMax)) {
19+
absMax = numbers[i];
20+
}
21+
}
22+
return absMax;
2923
}
3024
}

src/test/java/com/thealgorithms/maths/AbsoluteMaxTest.java

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,12 @@ public class AbsoluteMaxTest {
1010
@Test
1111
void testGetMaxValue() {
1212
assertEquals(16, AbsoluteMax.getMaxValue(-2, 0, 16));
13-
assertEquals(-10, AbsoluteMax.getMaxValue(3, -10, -2));
13+
assertEquals(-22, AbsoluteMax.getMaxValue(-3, -10, -22));
14+
assertEquals(-888, AbsoluteMax.getMaxValue(-888));
1415
}
1516

1617
@Test
1718
void testGetMaxValueWithNoArguments() {
18-
Exception exception = assertThrows(
19-
IllegalArgumentException.class,
20-
() -> AbsoluteMax.getMaxValue()
21-
);
22-
assertEquals("Numbers array cannot be empty", exception.getMessage());
19+
assertThrows(IllegalArgumentException.class, AbsoluteMax::getMaxValue);
2320
}
2421
}

0 commit comments

Comments
 (0)