Repository: TheAlgorithms/Java
Pull request #5749 (2024-10-13 03:36:50)

feat: Add `MorseCodeConverter` new algorithm with Junit tests
<!--
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/5749?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 `95.65217%` with `2 lines` in your changes missing coverage. Please review.
> Project coverage is 63.99%. Comparing base [(`4a03f42`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/4a03f420616a6773e9a5cdc304b1681e96d945bd?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`e667bdc`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/e667bdc2c0f43d2ce7301d157cd8d58e9284fd72?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/5749?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [.../thealgorithms/conversions/MorseCodeConverter.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5749?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fconversions%2FMorseCodeConverter.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9jb252ZXJzaW9ucy9Nb3JzZUNvZGVDb252ZXJ0ZXIuamF2YQ==) | 95.65% | [1 Missing and 1 partial :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5749?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    #5749      +/-   ##
============================================
+ Coverage     63.91%   63.99%   +0.08%     
- Complexity     4167     4175       +8     
============================================
  Files           582      583       +1     
  Lines         16302    16348      +46     
  Branches       3148     3154       +6     
============================================
+ Hits          10419    10462      +43     
- Misses         5457     5458       +1     
- Partials        426      428       +2     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5749?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).


Patch:
diff --git a/DIRECTORY.md b/DIRECTORY.md
index 521961c1..342aa37a 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -95,6 +95,7 @@
             * [IntegerToEnglish](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/IntegerToEnglish.java)
             * [IntegerToRoman](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/IntegerToRoman.java)
             * [IPConverter](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/IPConverter.java)
+            * [MorseCodeConverter](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/MorseCodeConverter.java)
             * [OctalToBinary](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/OctalToBinary.java)
             * [OctalToDecimal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/OctalToDecimal.java)
             * [OctalToHexadecimal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/OctalToHexadecimal.java)
@@ -733,6 +734,7 @@
             * [IntegerToEnglishTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/IntegerToEnglishTest.java)
             * [IntegerToRomanTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/IntegerToRomanTest.java)
             * [IPConverterTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/IPConverterTest.java)
+            * [MorseCodeConverterTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/MorseCodeConverterTest.java)
             * [OctalToBinaryTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java)
             * [OctalToDecimalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/OctalToDecimalTest.java)
             * [OctalToHexadecimalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/OctalToHexadecimalTest.java)
diff --git a/src/main/java/com/thealgorithms/conversions/MorseCodeConverter.java b/src/main/java/com/thealgorithms/conversions/MorseCodeConverter.java
new file mode 100644
index 00000000..a3973da0
--- /dev/null
+++ b/src/main/java/com/thealgorithms/conversions/MorseCodeConverter.java
@@ -0,0 +1,98 @@
+package com.thealgorithms.conversions;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Converts text to Morse code and vice-versa.
+ * Text to Morse code: Each letter is separated by a space and each word is separated by a pipe (|).
+ * Example: "HELLO WORLD" -> ".... . .-.. .-.. --- | .-- --- .-. .-.. -.."
+ *
+ * Morse code to text: Each letter is separated by a space and each word is separated by a pipe (|).
+ * Example: ".... . .-.. .-.. --- | .-- --- .-. .-.. -.." -> "HELLO WORLD"
+ *
+ * Applications: Used in radio communications and algorithmic challenges.
+ *
+ * @author Hardvan
+ */
+public final class MorseCodeConverter {
+    private MorseCodeConverter() {
+    }
+
+    private static final Map<Character, String> MORSE_MAP = new HashMap<>();
+    private static final Map<String, Character> REVERSE_MAP = new HashMap<>();
+
+    static {
+        MORSE_MAP.put('A', ".-");
+        MORSE_MAP.put('B', "-...");
+        MORSE_MAP.put('C', "-.-.");
+        MORSE_MAP.put('D', "-..");
+        MORSE_MAP.put('E', ".");
+        MORSE_MAP.put('F', "..-.");
+        MORSE_MAP.put('G', "--.");
+        MORSE_MAP.put('H', "....");
+        MORSE_MAP.put('I', "..");
+        MORSE_MAP.put('J', ".---");
+        MORSE_MAP.put('K', "-.-");
+        MORSE_MAP.put('L', ".-..");
+        MORSE_MAP.put('M', "--");
+        MORSE_MAP.put('N', "-.");
+        MORSE_MAP.put('O', "---");
+        MORSE_MAP.put('P', ".--.");
+        MORSE_MAP.put('Q', "--.-");
+        MORSE_MAP.put('R', ".-.");
+        MORSE_MAP.put('S', "...");
+        MORSE_MAP.put('T', "-");
+        MORSE_MAP.put('U', "..-");
+        MORSE_MAP.put('V', "...-");
+        MORSE_MAP.put('W', ".--");
+        MORSE_MAP.put('X', "-..-");
+        MORSE_MAP.put('Y', "-.--");
+        MORSE_MAP.put('Z', "--..");
+
+        // Build reverse map for decoding
+        MORSE_MAP.forEach((k, v) -> REVERSE_MAP.put(v, k));
+    }
+
+    /**
+     * Converts text to Morse code.
+     * Each letter is separated by a space and each word is separated by a pipe (|).
+     *
+     * @param text The text to convert to Morse code.
+     * @return The Morse code representation of the text.
+     */
+    public static String textToMorse(String text) {
+        StringBuilder morse = new StringBuilder();
+        String[] words = text.toUpperCase().split(" ");
+        for (int i = 0; i < words.length; i++) {
+            for (char c : words[i].toCharArray()) {
+                morse.append(MORSE_MAP.getOrDefault(c, "")).append(" ");
+            }
+            if (i < words.length - 1) {
+                morse.append("| ");
+            }
+        }
+        return morse.toString().trim();
+    }
+
+    /**
+     * Converts Morse code to text.
+     * Each letter is separated by a space and each word is separated by a pipe (|).
+     *
+     * @param morse The Morse code to convert to text.
+     * @return The text representation of the Morse code.
+     */
+    public static String morseToText(String morse) {
+        StringBuilder text = new StringBuilder();
+        String[] words = morse.split(" \\| ");
+        for (int i = 0; i < words.length; i++) {
+            for (String code : words[i].split(" ")) {
+                text.append(REVERSE_MAP.getOrDefault(code, '?'));
+            }
+            if (i < words.length - 1) {
+                text.append(" ");
+            }
+        }
+        return text.toString();
+    }
+}


Test patch:
diff --git a/src/test/java/com/thealgorithms/conversions/MorseCodeConverterTest.java b/src/test/java/com/thealgorithms/conversions/MorseCodeConverterTest.java
new file mode 100644
index 00000000..153b632a
--- /dev/null
+++ b/src/test/java/com/thealgorithms/conversions/MorseCodeConverterTest.java
@@ -0,0 +1,19 @@
+package com.thealgorithms.conversions;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.junit.jupiter.api.Test;
+
+public class MorseCodeConverterTest {
+
+    @Test
+    public void testTextToMorse() {
+        assertEquals(".- -...", MorseCodeConverter.textToMorse("AB"));
+        assertEquals(".... . .-.. .-.. --- | .-- --- .-. .-.. -..", MorseCodeConverter.textToMorse("HELLO WORLD"));
+    }
+
+    @Test
+    public void testMorseToText() {
+        assertEquals("AB", MorseCodeConverter.morseToText(".- -..."));
+    }
+}