Skip to content

update AbsoluteMax #4140

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 13 additions & 19 deletions src/main/java/com/thealgorithms/maths/AbsoluteMax.java
Original file line number Diff line number Diff line change
@@ -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;
}
}
9 changes: 3 additions & 6 deletions src/test/java/com/thealgorithms/maths/AbsoluteMaxTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}