Code refactor for AbsoluteValue improvements (#3018)

Fix #3017

Co-authored-by: Yang Libin <szuyanglb@outlook.com>
This commit is contained in:
Cristiano Jesus 2022-04-20 09:17:44 +01:00 committed by GitHub
parent 64b624efb2
commit 5eed0849ef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 17 deletions

View File

@ -1,26 +1,14 @@
package com.thealgorithms.maths; package com.thealgorithms.maths;
import java.util.Random;
public class AbsoluteValue { public class AbsoluteValue {
public static void main(String[] args) {
Random random = new Random();
/* test 1000 random numbers */
for (int i = 1; i <= 1000; ++i) {
int randomNumber = random.nextInt();
assert absVal(randomNumber) == Math.abs(randomNumber);
}
}
/** /**
* If value is less than zero, make value positive. * Returns the absolute value of a number.
* *
* @param value a number * @param number The number to be transformed
* @return the absolute value of a number * @return The absolute value of the {@code number}
*/ */
public static int absVal(int value) { public static int getAbsValue(int number) {
return value < 0 ? -value : value; return number < 0 ? -number : number;
} }
} }

View File

@ -0,0 +1,18 @@
package com.thealgorithms.maths;
import org.junit.jupiter.api.Test;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AbsoluteValueTest {
@Test
void testGetAbsValue() {
Stream.generate(() -> ThreadLocalRandom.current().nextInt())
.limit(1000)
.forEach(number -> assertEquals(Math.abs(number), AbsoluteValue.getAbsValue(number)));
}
}