Skip to content

Code refactor for AbsoluteMin improvements #3022

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
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
44 changes: 20 additions & 24 deletions src/main/java/com/thealgorithms/maths/AbsoluteMin.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,31 @@

import java.util.Arrays;

/**
* description:
*
* <p>
* absMin([0, 5, 1, 11]) = 0, absMin([3 , -10, -2]) = -2
*/
public class AbsoluteMin {

public static void main(String[] args) {
int[] testnums = {4, 0, 16};
assert absMin(testnums) == 0;

int[] numbers = {3, -10, -2};
System.out.println("absMin(" + Arrays.toString(numbers) + ") = " + absMin(numbers));
}

/**
* get the value, returns the absolute min value min
* Compares the numbers given as arguments to get the absolute min value.
*
* @param numbers contains elements
* @return the absolute min value
* @param numbers The numbers to compare
* @return The absolute min value
*/
public static int absMin(int[] numbers) {
int absMinValue = numbers[0];
for (int i = 1, length = numbers.length; i < length; ++i) {
if (Math.abs(numbers[i]) < Math.abs(absMinValue)) {
absMinValue = numbers[i];
}
public static int getMinValue(int... numbers) {
if (numbers.length == 0) {
throw new IllegalArgumentException("Numbers array cannot be empty");
}
return absMinValue;

var absMinWrapper = new Object() {
int value = numbers[0];
};

Arrays.stream(numbers)
.skip(1)
.forEach(number -> {
if (Math.abs(number) < Math.abs(absMinWrapper.value)) {
absMinWrapper.value = number;
}
});

return absMinWrapper.value;
}
}
21 changes: 21 additions & 0 deletions src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java
Original file line number Diff line number Diff line change
@@ -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 AbsoluteMinTest {

@Test
void testGetMinValue() {
assertEquals(0, AbsoluteMin.getMinValue(4, 0, 16));
assertEquals(-2, AbsoluteMin.getMinValue(3, -10, -2));
}

@Test
void testGetMinValueWithNoArguments() {
Exception exception = assertThrows(IllegalArgumentException.class, () -> AbsoluteMin.getMinValue());
assertEquals("Numbers array cannot be empty", exception.getMessage());
}
}