Skip to content

Commit 64b624e

Browse files
Code refactor for AbsoluteMax improvements (TheAlgorithms#3020)
Fix TheAlgorithms#3019 Co-authored-by: Yang Libin <szuyanglb@outlook.com>
1 parent 02375e0 commit 64b624e

File tree

2 files changed

+41
-24
lines changed

2 files changed

+41
-24
lines changed

src/main/java/com/thealgorithms/maths/AbsoluteMax.java

Lines changed: 20 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -2,35 +2,31 @@
22

33
import java.util.Arrays;
44

5-
/**
6-
* description:
7-
*
8-
* <p>
9-
* absMax([0, 5, 1, 11]) = 11, absMax([3 , -10, -2]) = -10
10-
*/
115
public class AbsoluteMax {
126

13-
public static void main(String[] args) {
14-
int[] testnums = {-2, 0, 16};
15-
assert absMax(testnums) == 16;
16-
17-
int[] numbers = {3, -10, -2};
18-
System.out.println("absMax(" + Arrays.toString(numbers) + ") = " + absMax(numbers));
19-
}
20-
217
/**
22-
* get the value, return the absolute max value
8+
* Compares the numbers given as arguments to get the absolute max value.
239
*
24-
* @param numbers contains elements
25-
* @return the absolute max value
10+
* @param numbers The numbers to compare
11+
* @return The absolute max value
2612
*/
27-
public static int absMax(int[] numbers) {
28-
int absMaxValue = numbers[0];
29-
for (int i = 1, length = numbers.length; i < length; ++i) {
30-
if (Math.abs(numbers[i]) > Math.abs(absMaxValue)) {
31-
absMaxValue = numbers[i];
32-
}
13+
public static int getMaxValue(int... numbers) {
14+
if (numbers.length == 0) {
15+
throw new IllegalArgumentException("Numbers array cannot be empty");
3316
}
34-
return absMaxValue;
17+
18+
var absMaxWrapper = new Object() {
19+
int value = numbers[0];
20+
};
21+
22+
Arrays.stream(numbers)
23+
.skip(1)
24+
.forEach(number -> {
25+
if (Math.abs(number) > Math.abs(absMaxWrapper.value)) {
26+
absMaxWrapper.value = number;
27+
}
28+
});
29+
30+
return absMaxWrapper.value;
3531
}
3632
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.thealgorithms.maths;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.assertEquals;
6+
import static org.junit.jupiter.api.Assertions.assertThrows;
7+
8+
public class AbsoluteMaxTest {
9+
10+
@Test
11+
void testGetMaxValue() {
12+
assertEquals(16, AbsoluteMax.getMaxValue(-2, 0, 16));
13+
assertEquals(-10, AbsoluteMax.getMaxValue(3, -10, -2));
14+
}
15+
16+
@Test
17+
void testGetMaxValueWithNoArguments() {
18+
Exception exception = assertThrows(IllegalArgumentException.class, () -> AbsoluteMax.getMaxValue());
19+
assertEquals("Numbers array cannot be empty", exception.getMessage());
20+
}
21+
}

0 commit comments

Comments
 (0)