From d1601560032b75f347adf987417eda0fdc2d95f4 Mon Sep 17 00:00:00 2001 From: duyuanch <680888@gmail.com> Date: Mon, 3 Apr 2023 22:39:17 +0800 Subject: [PATCH] Update AbsoluteMax (#4140) --- .../com/thealgorithms/maths/AbsoluteMax.java | 32 ++++++++----------- .../thealgorithms/maths/AbsoluteMaxTest.java | 9 ++---- 2 files changed, 16 insertions(+), 25 deletions(-) diff --git a/src/main/java/com/thealgorithms/maths/AbsoluteMax.java b/src/main/java/com/thealgorithms/maths/AbsoluteMax.java index bb89fb23..64338297 100644 --- a/src/main/java/com/thealgorithms/maths/AbsoluteMax.java +++ b/src/main/java/com/thealgorithms/maths/AbsoluteMax.java @@ -1,30 +1,24 @@ package com.thealgorithms.maths; -import java.util.Arrays; - 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 - * @return The absolute max value + * @param numbers The numbers to compare. + * @return The absolute maximum value. + * @throws IllegalArgumentException If the input array is empty or null. */ public static int getMaxValue(int... numbers) { - if (numbers.length == 0) { - throw new IllegalArgumentException("Numbers array cannot be empty"); + if (numbers == null || numbers.length == 0) { + throw new IllegalArgumentException("Numbers array cannot be empty or null"); } - - var absMaxWrapper = new Object() { - int value = numbers[0]; - }; - - Arrays - .stream(numbers) - .skip(1) - .filter(number -> Math.abs(number) > Math.abs(absMaxWrapper.value)) - .forEach(number -> absMaxWrapper.value = number); - - return absMaxWrapper.value; + int absMax = numbers[0]; + for (int i = 1; i < numbers.length; i++) { + if (Math.abs(numbers[i]) > Math.abs(absMax)) { + absMax = numbers[i]; + } + } + return absMax; } } diff --git a/src/test/java/com/thealgorithms/maths/AbsoluteMaxTest.java b/src/test/java/com/thealgorithms/maths/AbsoluteMaxTest.java index 78a8c093..85ffb91e 100644 --- a/src/test/java/com/thealgorithms/maths/AbsoluteMaxTest.java +++ b/src/test/java/com/thealgorithms/maths/AbsoluteMaxTest.java @@ -10,15 +10,12 @@ public class AbsoluteMaxTest { @Test void testGetMaxValue() { 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 void testGetMaxValueWithNoArguments() { - Exception exception = assertThrows( - IllegalArgumentException.class, - () -> AbsoluteMax.getMaxValue() - ); - assertEquals("Numbers array cannot be empty", exception.getMessage()); + assertThrows(IllegalArgumentException.class, AbsoluteMax::getMaxValue); } }