Code refactor for AbsoluteMax improvements (#3020)

Fix #3019

Co-authored-by: Yang Libin <szuyanglb@outlook.com>
This commit is contained in:
Cristiano Jesus 2022-04-20 09:15:30 +01:00 committed by GitHub
parent 02375e0683
commit 64b624efb2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 41 additions and 24 deletions

View File

@ -2,35 +2,31 @@ package com.thealgorithms.maths;
import java.util.Arrays;
/**
* description:
*
* <p>
* absMax([0, 5, 1, 11]) = 11, absMax([3 , -10, -2]) = -10
*/
public class AbsoluteMax {
public static void main(String[] args) {
int[] testnums = {-2, 0, 16};
assert absMax(testnums) == 16;
int[] numbers = {3, -10, -2};
System.out.println("absMax(" + Arrays.toString(numbers) + ") = " + absMax(numbers));
}
/**
* get the value, return the absolute max value
* Compares the numbers given as arguments to get the absolute max value.
*
* @param numbers contains elements
* @return the absolute max value
* @param numbers The numbers to compare
* @return The absolute max value
*/
public static int absMax(int[] numbers) {
int absMaxValue = numbers[0];
for (int i = 1, length = numbers.length; i < length; ++i) {
if (Math.abs(numbers[i]) > Math.abs(absMaxValue)) {
absMaxValue = numbers[i];
}
public static int getMaxValue(int... numbers) {
if (numbers.length == 0) {
throw new IllegalArgumentException("Numbers array cannot be empty");
}
return absMaxValue;
var absMaxWrapper = new Object() {
int value = numbers[0];
};
Arrays.stream(numbers)
.skip(1)
.forEach(number -> {
if (Math.abs(number) > Math.abs(absMaxWrapper.value)) {
absMaxWrapper.value = number;
}
});
return absMaxWrapper.value;
}
}

View File

@ -0,0 +1,21 @@
package com.thealgorithms.maths;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class AbsoluteMaxTest {
@Test
void testGetMaxValue() {
assertEquals(16, AbsoluteMax.getMaxValue(-2, 0, 16));
assertEquals(-10, AbsoluteMax.getMaxValue(3, -10, -2));
}
@Test
void testGetMaxValueWithNoArguments() {
Exception exception = assertThrows(IllegalArgumentException.class, () -> AbsoluteMax.getMaxValue());
assertEquals("Numbers array cannot be empty", exception.getMessage());
}
}