Skip to content

tests: add tests for GenericRoot #4276

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
merged 5 commits into from
Aug 3, 2023
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
36 changes: 18 additions & 18 deletions src/main/java/com/thealgorithms/maths/GenericRoot.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,27 @@
* Algorithm explanation:
* https://technotip.com/6774/c-program-to-find-generic-root-of-a-number/#:~:text=Generic%20Root%3A%20of%20a%20number,get%20a%20single%2Ddigit%20output.&text=For%20Example%3A%20If%20user%20input,%2B%204%20%2B%205%20%3D%2015.
*/
public class GenericRoot {
public final class GenericRoot {
private GenericRoot() {
}

private static int base = 10;

public static void main(String[] args) {
int number1 = 1234;
int number2 = 12345;
int result1 = genericRoot(number1);
int result2 = genericRoot(number2);
System.out.println("Generic root of " + number1 + " is: " + result1);
System.out.println("Generic root of " + number2 + " is: " + result2);
private static int sumOfDigits(final int n) {
assert n >= 0;
if (n < base) {
return n;
}
return n % base + sumOfDigits(n / base);
}

private static int genericRoot(int n) {
int root = 0;
while (n > 0 || root > 9) {
if (n == 0) {
n = root;
root = 0;
}
root += n % 10;
n /= 10;
public static int genericRoot(final int n) {
if (n < 0) {
return genericRoot(-n);
}
if (n > base) {
return genericRoot(sumOfDigits(n));
}
return root;
return n;
}
}
24 changes: 24 additions & 0 deletions src/test/java/com/thealgorithms/maths/GenericRootTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.thealgorithms.maths;

import static java.util.Map.entry;
import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.Map;
import org.junit.jupiter.api.Test;

public class GenericRootTest {
private final Map<Integer, Integer> testCases = Map.ofEntries(entry(0, 0), entry(1, 1), entry(12345, 6), entry(123, 6), entry(15937, 7), entry(222222, 3), entry(99999, 9));
@Test
public void testGenericRoot() {
for (final var tc : testCases.entrySet()) {
assertEquals(tc.getValue(), GenericRoot.genericRoot(tc.getKey()));
}
}

@Test
public void testGenericRootWithNegativeInputs() {
for (final var tc : testCases.entrySet()) {
assertEquals(tc.getValue(), GenericRoot.genericRoot(-tc.getKey()));
}
}
}