Update AbsoluteMax (#4140)
This commit is contained in:
parent
ad72c28d91
commit
d160156003
@ -1,30 +1,24 @@
|
|||||||
package com.thealgorithms.maths;
|
package com.thealgorithms.maths;
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
|
|
||||||
public class AbsoluteMax {
|
public class AbsoluteMax {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Compares the numbers given as arguments to get the absolute max value.
|
* Finds the absolute maximum value among the given numbers.
|
||||||
*
|
*
|
||||||
* @param numbers The numbers to compare
|
* @param numbers The numbers to compare.
|
||||||
* @return The absolute max value
|
* @return The absolute maximum value.
|
||||||
|
* @throws IllegalArgumentException If the input array is empty or null.
|
||||||
*/
|
*/
|
||||||
public static int getMaxValue(int... numbers) {
|
public static int getMaxValue(int... numbers) {
|
||||||
if (numbers.length == 0) {
|
if (numbers == null || numbers.length == 0) {
|
||||||
throw new IllegalArgumentException("Numbers array cannot be empty");
|
throw new IllegalArgumentException("Numbers array cannot be empty or null");
|
||||||
}
|
}
|
||||||
|
int absMax = numbers[0];
|
||||||
var absMaxWrapper = new Object() {
|
for (int i = 1; i < numbers.length; i++) {
|
||||||
int value = numbers[0];
|
if (Math.abs(numbers[i]) > Math.abs(absMax)) {
|
||||||
};
|
absMax = numbers[i];
|
||||||
|
}
|
||||||
Arrays
|
}
|
||||||
.stream(numbers)
|
return absMax;
|
||||||
.skip(1)
|
|
||||||
.filter(number -> Math.abs(number) > Math.abs(absMaxWrapper.value))
|
|
||||||
.forEach(number -> absMaxWrapper.value = number);
|
|
||||||
|
|
||||||
return absMaxWrapper.value;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -10,15 +10,12 @@ public class AbsoluteMaxTest {
|
|||||||
@Test
|
@Test
|
||||||
void testGetMaxValue() {
|
void testGetMaxValue() {
|
||||||
assertEquals(16, AbsoluteMax.getMaxValue(-2, 0, 16));
|
assertEquals(16, AbsoluteMax.getMaxValue(-2, 0, 16));
|
||||||
assertEquals(-10, AbsoluteMax.getMaxValue(3, -10, -2));
|
assertEquals(-22, AbsoluteMax.getMaxValue(-3, -10, -22));
|
||||||
|
assertEquals(-888, AbsoluteMax.getMaxValue(-888));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testGetMaxValueWithNoArguments() {
|
void testGetMaxValueWithNoArguments() {
|
||||||
Exception exception = assertThrows(
|
assertThrows(IllegalArgumentException.class, AbsoluteMax::getMaxValue);
|
||||||
IllegalArgumentException.class,
|
|
||||||
() -> AbsoluteMax.getMaxValue()
|
|
||||||
);
|
|
||||||
assertEquals("Numbers array cannot be empty", exception.getMessage());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user