Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
feat: Code refactor for AbsoluteValue improvements
I'm refactoring some classes from the `maths` package to have a cleaner,
more concise, easier to maintain and better documented code.

I've also updated the code to use features from newer versions of Java
and I've created some unit tests because it was missing unit tests for
AbsoluteValue (I'm using now unit tests instead of main method to test the
feature).

Resolves: #3017
  • Loading branch information
cristbjesus committed Apr 19, 2022
commit 510ac99e705c772f1be1026c2122936d6ddf9e18
22 changes: 5 additions & 17 deletions src/main/java/com/thealgorithms/maths/AbsoluteValue.java
Original file line number Diff line number Diff line change
@@ -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;
}
}
18 changes: 18 additions & 0 deletions src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java
Original file line number Diff line number Diff line change
@@ -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)));
}
}