From 5eed0849ef4734e3faec8fa21d798c2927ec3b4e Mon Sep 17 00:00:00 2001 From: Cristiano Jesus Date: Wed, 20 Apr 2022 09:17:44 +0100 Subject: [PATCH] Code refactor for AbsoluteValue improvements (#3018) Fix #3017 Co-authored-by: Yang Libin --- .../thealgorithms/maths/AbsoluteValue.java | 22 +++++-------------- .../maths/AbsoluteValueTest.java | 18 +++++++++++++++ 2 files changed, 23 insertions(+), 17 deletions(-) create mode 100644 src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java diff --git a/src/main/java/com/thealgorithms/maths/AbsoluteValue.java b/src/main/java/com/thealgorithms/maths/AbsoluteValue.java index dfd00f86..60741364 100644 --- a/src/main/java/com/thealgorithms/maths/AbsoluteValue.java +++ b/src/main/java/com/thealgorithms/maths/AbsoluteValue.java @@ -1,26 +1,14 @@ package com.thealgorithms.maths; -import java.util.Random; - 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 - * @return the absolute value of a number + * @param number The number to be transformed + * @return The absolute value of the {@code number} */ - public static int absVal(int value) { - return value < 0 ? -value : value; + public static int getAbsValue(int number) { + return number < 0 ? -number : number; } } diff --git a/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java b/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java new file mode 100644 index 00000000..8b95eaec --- /dev/null +++ b/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java @@ -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))); + } +}