Skip to content

Commit 02375e0

Browse files
authored
Code refactor for AbsoluteMin improvements (TheAlgorithms#3022)
Fix TheAlgorithms#3021
1 parent 719e1d8 commit 02375e0

File tree

2 files changed

+41
-24
lines changed

2 files changed

+41
-24
lines changed

src/main/java/com/thealgorithms/maths/AbsoluteMin.java

Lines changed: 20 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -2,35 +2,31 @@
22

33
import java.util.Arrays;
44

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

13-
public static void main(String[] args) {
14-
int[] testnums = {4, 0, 16};
15-
assert absMin(testnums) == 0;
16-
17-
int[] numbers = {3, -10, -2};
18-
System.out.println("absMin(" + Arrays.toString(numbers) + ") = " + absMin(numbers));
19-
}
20-
217
/**
22-
* get the value, returns the absolute min value min
8+
* Compares the numbers given as arguments to get the absolute min value.
239
*
24-
* @param numbers contains elements
25-
* @return the absolute min value
10+
* @param numbers The numbers to compare
11+
* @return The absolute min value
2612
*/
27-
public static int absMin(int[] numbers) {
28-
int absMinValue = numbers[0];
29-
for (int i = 1, length = numbers.length; i < length; ++i) {
30-
if (Math.abs(numbers[i]) < Math.abs(absMinValue)) {
31-
absMinValue = numbers[i];
32-
}
13+
public static int getMinValue(int... numbers) {
14+
if (numbers.length == 0) {
15+
throw new IllegalArgumentException("Numbers array cannot be empty");
3316
}
34-
return absMinValue;
17+
18+
var absMinWrapper = new Object() {
19+
int value = numbers[0];
20+
};
21+
22+
Arrays.stream(numbers)
23+
.skip(1)
24+
.forEach(number -> {
25+
if (Math.abs(number) < Math.abs(absMinWrapper.value)) {
26+
absMinWrapper.value = number;
27+
}
28+
});
29+
30+
return absMinWrapper.value;
3531
}
3632
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.thealgorithms.maths;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.assertEquals;
6+
import static org.junit.jupiter.api.Assertions.assertThrows;
7+
8+
public class AbsoluteMinTest {
9+
10+
@Test
11+
void testGetMinValue() {
12+
assertEquals(0, AbsoluteMin.getMinValue(4, 0, 16));
13+
assertEquals(-2, AbsoluteMin.getMinValue(3, -10, -2));
14+
}
15+
16+
@Test
17+
void testGetMinValueWithNoArguments() {
18+
Exception exception = assertThrows(IllegalArgumentException.class, () -> AbsoluteMin.getMinValue());
19+
assertEquals("Numbers array cannot be empty", exception.getMessage());
20+
}
21+
}

0 commit comments

Comments
 (0)