Repository: TheAlgorithms/Java
Pull request #6110 (2024-12-23 12:10:10)

Improvements to Vampire Number
Several improvements to maths/VampireNumber code:

1. Fixes a bug in same length of fangs detection for pseudo vampire numbers. Now it is done in the most straight-forward way.
2. Adds tests for the VampireNumber class.
3. Fixed several typos in code and comments.
4. Generally simplifies code and improves readability.

<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

<!-- For completed items, change [ ] to [x] -->

- [X] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [X] This pull request is all my own work -- I have not plagiarized it.
- [X] All filenames are in PascalCase.
- [X] All functions and variable names follow Java naming conventions.
- [X] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [X] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/6110?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
Attention: Patch coverage is `52.38095%` with `10 lines` in your changes missing coverage. Please review.
> Project coverage is 73.74%. Comparing base [(`2fff579`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/2fff5790450c1b58a329d1ec576c6bc155b503ea?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`82828cd`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/82828cd4c28386586ab44cffed7070fa5683bfc2?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

| [Files with missing lines](https://app.codecov.io/gh/TheAlgorithms/Java/pull/6110?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [...in/java/com/thealgorithms/maths/VampireNumber.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/6110?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fmaths%2FVampireNumber.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9tYXRocy9WYW1waXJlTnVtYmVyLmphdmE=) | 52.38% | [9 Missing and 1 partial :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/6110?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) |

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #6110      +/-   ##
============================================
+ Coverage     73.64%   73.74%   +0.10%     
- Complexity     5112     5119       +7     
============================================
  Files           658      658              
  Lines         17649    17641       -8     
  Branches       3396     3394       -2     
============================================
+ Hits          12997    13010      +13     
+ Misses         4147     4127      -20     
+ Partials        505      504       -1     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/6110?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

Shisoik: IMHO, limiting tests to just 3 static imports and forbidding to static import org.junit.jupiter.api.Assertions.* is too strict and actually hurts readability. Not gonna argue, juest a thought.

Patch:
diff --git a/src/main/java/com/thealgorithms/maths/VampireNumber.java b/src/main/java/com/thealgorithms/maths/VampireNumber.java
index 8820f8a2..45bb9a58 100644
--- a/src/main/java/com/thealgorithms/maths/VampireNumber.java
+++ b/src/main/java/com/thealgorithms/maths/VampireNumber.java
@@ -1,78 +1,48 @@
 package com.thealgorithms.maths;
 
 import java.util.ArrayList;
-import java.util.Collections;
 
 /**
- * n number theory, a vampire number (or true vampire number) is a composite
+ * In number theory, a vampire number (or true vampire number) is a composite
  * natural number with an even number of digits, that can be factored into two
  * natural numbers each with half as many digits as the original number and not
  * both with trailing zeroes, where the two factors contain precisely all the
  * digits of the original number, in any order, counting multiplicity. The first
- * vampire number is 1260 = 21 × 60. *
+ * vampire number is 1260 = 21 × 60.
  *
- * <p>
- * link: https://en.wikipedia.org/wiki/Vampire_number *
- *
- * <p>
+ * @see <a href='https://en.wikipedia.org/wiki/Vampire_number'>Vampire number on Wikipedia</a>
  */
 public final class VampireNumber {
+    // Forbid instantiation.
     private VampireNumber() {
     }
 
-    public static void main(String[] args) {
-        test(10, 1000);
-    }
-
-    static void test(int startValue, int stopValue) {
-        int countofRes = 1;
-        StringBuilder res = new StringBuilder();
-
-        for (int i = startValue; i <= stopValue; i++) {
-            for (int j = i; j <= stopValue; j++) {
-                // System.out.println(i+ " "+ j);
-                if (isVampireNumber(i, j, true)) {
-                    countofRes++;
-                    res.append("").append(countofRes).append(": = ( ").append(i).append(",").append(j).append(" = ").append(i * j).append(")").append("\n");
-                }
-            }
-        }
-        System.out.println(res);
-    }
-
-    static boolean isVampireNumber(int a, int b, boolean noPseudoVamireNumbers) {
-        // this is for pseudoVampireNumbers  pseudovampire number need not be of length n/2 digits
-        // for example 126 = 6 x 21
-        if (noPseudoVamireNumbers) {
-            if (a * 10 <= b || b * 10 <= a) {
-                return false;
-            }
+    static boolean isVampireNumber(int a, int b, boolean ignorePseudoVampireNumbers) {
+        // Pseudo vampire numbers don't have to be of n/2 digits. E.g., 126 = 6 x 21 is such a number.
+        if (ignorePseudoVampireNumbers && String.valueOf(a).length() != String.valueOf(b).length()) {
+            return false;
         }
 
-        String mulDigits = splitIntoDigits(a * b, 0);
-        String faktorDigits = splitIntoDigits(a, b);
+        String mulDigits = splitIntoSortedDigits(a * b);
+        String factorDigits = splitIntoSortedDigits(a, b);
 
-        return mulDigits.equals(faktorDigits);
+        return mulDigits.equals(factorDigits);
     }
 
-    // methode to Split the numbers to Digits
-    static String splitIntoDigits(int num, int num2) {
-        StringBuilder res = new StringBuilder();
-
+    // Method to split a pair of numbers to digits and sort them in the ascending order.
+    static String splitIntoSortedDigits(int... nums) {
+        // Collect all digits in a list.
         ArrayList<Integer> digits = new ArrayList<>();
-        while (num > 0) {
-            digits.add(num % 10);
-            num /= 10;
-        }
-        while (num2 > 0) {
-            digits.add(num2 % 10);
-            num2 /= 10;
-        }
-        Collections.sort(digits);
-        for (int i : digits) {
-            res.append(i);
+        for (int num : nums) {
+            while (num > 0) {
+                digits.add(num % 10);
+                num /= 10;
+            }
         }
 
+        // Sort all digits and convert to String.
+        StringBuilder res = new StringBuilder();
+        digits.stream().sorted().forEach(res::append);
         return res.toString();
     }
 }


Test patch:
diff --git a/src/test/java/com/thealgorithms/maths/VampireNumberTest.java b/src/test/java/com/thealgorithms/maths/VampireNumberTest.java
new file mode 100644
index 00000000..6f331f12
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/VampireNumberTest.java
@@ -0,0 +1,32 @@
+package com.thealgorithms.maths;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+class VampireNumberTest {
+    @Test
+    void areVampireNumbers() {
+        Assertions.assertTrue(VampireNumber.isVampireNumber(15, 93, true));
+        Assertions.assertTrue(VampireNumber.isVampireNumber(135, 801, true));
+        Assertions.assertTrue(VampireNumber.isVampireNumber(201, 600, true));
+    }
+
+    @Test
+    void arePseudoVampireNumbers() {
+        Assertions.assertTrue(VampireNumber.isVampireNumber(150, 93, false));
+        Assertions.assertTrue(VampireNumber.isVampireNumber(546, 84, false));
+        Assertions.assertTrue(VampireNumber.isVampireNumber(641, 65, false));
+    }
+
+    @Test
+    void areNotVampireNumbers() {
+        Assertions.assertFalse(VampireNumber.isVampireNumber(51, 39, false));
+        Assertions.assertFalse(VampireNumber.isVampireNumber(51, 39, true));
+    }
+
+    @Test
+    void testSplitIntoSortedDigits() {
+        Assertions.assertEquals("123", VampireNumber.splitIntoSortedDigits(321));
+        Assertions.assertEquals("02234", VampireNumber.splitIntoSortedDigits(20, 324));
+    }
+}