Repository: TheAlgorithms/Java
Pull request #5221 (2024-06-12 11:29:29)

refactor: redesign `LetterCombinationsOfPhoneNumber`
Related to #5164

- [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/5221?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 `84.61538%` with `4 lines` in your changes missing coverage. Please review.
> Project coverage is 38.74%. Comparing base [(`3ecd135`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/3ecd13508a8ebe533afe3486bac66cb3ab54cecb?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`61e2a98`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/61e2a9826e1833a3fb58a4f389eb52502522c59c?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

| [Files](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5221?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [...ithms/strings/LetterCombinationsOfPhoneNumber.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5221?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fstrings%2FLetterCombinationsOfPhoneNumber.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9zdHJpbmdzL0xldHRlckNvbWJpbmF0aW9uc09mUGhvbmVOdW1iZXIuamF2YQ==) | 84.61% | [3 Missing and 1 partial :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5221?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    #5221      +/-   ##
============================================
+ Coverage     38.72%   38.74%   +0.01%     
- Complexity     2383     2386       +3     
============================================
  Files           517      517              
  Lines         15392    15392              
  Branches       2954     2954              
============================================
+ Hits           5961     5963       +2     
+ Misses         9144     9141       -3     
- Partials        287      288       +1     
```



</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5221?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/src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java b/src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java
index 2e3ee25f..38c6bc13 100644
--- a/src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java
+++ b/src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java
@@ -5,49 +5,61 @@ import java.util.Collections;
 import java.util.List;
 
 public final class LetterCombinationsOfPhoneNumber {
+
+    private static final char EMPTY = '\0';
+
+    // Mapping of numbers to corresponding letters on a phone keypad
+    private static final String[] KEYPAD = new String[] {" ", String.valueOf(EMPTY), "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
+
     private LetterCombinationsOfPhoneNumber() {
     }
 
-    static Character[][] numberToCharMap;
-
-    protected static List<String> printWords(int[] numbers, int len, int numIndex, String s) {
-        if (len == numIndex) {
-            return new ArrayList<>(Collections.singleton(s));
+    /**
+     * Generates a list of all possible letter combinations that the provided
+     * array of numbers could represent on a phone keypad.
+     *
+     * @param numbers an array of integers representing the phone numbers
+     * @return a list of possible letter combinations
+     */
+    public static List<String> getCombinations(int[] numbers) {
+        if (numbers == null) {
+            return List.of("");
         }
+        return generateCombinations(numbers, 0, new StringBuilder());
+    }
 
-        List<String> stringList = new ArrayList<>();
+    /**
+     * Recursive method to generate combinations of letters from the phone keypad.
+     *
+     * @param numbers the input array of phone numbers
+     * @param index   the current index in the numbers array being processed
+     * @param current a StringBuilder holding the current combination of letters
+     * @return a list of letter combinations formed from the given numbers
+     */
+    private static List<String> generateCombinations(int[] numbers, int index, StringBuilder current) {
+        // Base case: if we've processed all numbers, return the current combination
+        if (index == numbers.length) {
+            return new ArrayList<>(Collections.singletonList(current.toString()));
+        }
 
-        for (int i = 0; i < numberToCharMap[numbers[numIndex]].length; i++) {
-            String sCopy = String.copyValueOf(s.toCharArray());
-            sCopy = sCopy.concat(numberToCharMap[numbers[numIndex]][i].toString());
-            stringList.addAll(printWords(numbers, len, numIndex + 1, sCopy));
+        final var number = numbers[index];
+        if (number < 0 || number > 9) {
+            throw new IllegalArgumentException("Input numbers must in the range [0, 9]");
         }
-        return stringList;
-    }
 
-    private static void printWords(int[] numbers) {
-        generateNumberToCharMap();
-        List<String> stringList = printWords(numbers, numbers.length, 0, "");
-        stringList.stream().forEach(System.out::println);
-    }
+        List<String> combinations = new ArrayList<>();
 
-    protected static void generateNumberToCharMap() {
-        numberToCharMap = new Character[10][5];
-        numberToCharMap[0] = new Character[] {'\0'};
-        numberToCharMap[1] = new Character[] {'\0'};
-        numberToCharMap[2] = new Character[] {'a', 'b', 'c'};
-        numberToCharMap[3] = new Character[] {'d', 'e', 'f'};
-        numberToCharMap[4] = new Character[] {'g', 'h', 'i'};
-        numberToCharMap[5] = new Character[] {'j', 'k', 'l'};
-        numberToCharMap[6] = new Character[] {'m', 'n', 'o'};
-        numberToCharMap[7] = new Character[] {'p', 'q', 'r', 's'};
-        numberToCharMap[8] = new Character[] {'t', 'u', 'v'};
-        numberToCharMap[9] = new Character[] {'w', 'x', 'y', 'z'};
-    }
+        // Iterate over each letter and recurse to generate further combinations
+        for (char letter : KEYPAD[number].toCharArray()) {
+            if (letter != EMPTY) {
+                current.append(letter);
+            }
+            combinations.addAll(generateCombinations(numbers, index + 1, current));
+            if (letter != EMPTY) {
+                current.deleteCharAt(current.length() - 1); // Backtrack by removing the last appended letter
+            }
+        }
 
-    // Driver code
-    public static void main(String[] args) {
-        int[] number = {2, 3, 4};
-        printWords(number);
+        return combinations;
     }
 }


Test patch:
diff --git a/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java b/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java
index 4ffbddcb..dcdb7d5b 100644
--- a/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java
+++ b/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java
@@ -1,45 +1,37 @@
 package com.thealgorithms.strings;
 
-import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
-import java.util.Arrays;
 import java.util.List;
-import org.junit.jupiter.api.Test;
+import java.util.stream.Stream;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
 
 public class LetterCombinationsOfPhoneNumberTest {
 
-    @Test
-    public void letterCombinationsOfPhoneNumber() {
-        LetterCombinationsOfPhoneNumber.generateNumberToCharMap();
-
-        // ** Test 1 **
-        // Input: digits = ""
-        // Output: []
-        int[] numbers1 = {};
-        List<String> output1 = Arrays.asList("");
-        assertTrue(LetterCombinationsOfPhoneNumber.printWords(numbers1, numbers1.length, 0, "").equals(output1));
+    @ParameterizedTest
+    @MethodSource("provideTestCases")
+    public void testLetterCombinationsOfPhoneNumber(int[] numbers, List<String> expectedOutput) {
+        assertEquals(expectedOutput, LetterCombinationsOfPhoneNumber.getCombinations(numbers));
+    }
 
-        // ** Test 2 **
-        // Input: digits = "2"
-        // Output: ["a","b","c"]
-        int[] numbers2 = {2};
-        List<String> output2 = Arrays.asList("a", "b", "c");
-        assertTrue(LetterCombinationsOfPhoneNumber.printWords(numbers2, numbers2.length, 0, "").equals(output2));
+    @ParameterizedTest
+    @MethodSource("wrongInputs")
+    void throwsForWrongInput(int[] numbers) {
+        assertThrows(IllegalArgumentException.class, () -> LetterCombinationsOfPhoneNumber.getCombinations(numbers));
+    }
 
-        // ** Test 3 **
-        // Input: digits = "23"
-        // Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
-        int[] numbers3 = {2, 3};
-        List<String> output3 = Arrays.asList("ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf");
-        assertTrue(LetterCombinationsOfPhoneNumber.printWords(numbers3, numbers3.length, 0, "").equals(output3));
+    private static Stream<Arguments> provideTestCases() {
+        return Stream.of(Arguments.of(null, List.of("")), Arguments.of(new int[] {}, List.of("")), Arguments.of(new int[] {2}, List.of("a", "b", "c")), Arguments.of(new int[] {2, 3}, List.of("ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf")),
+            Arguments.of(new int[] {2, 3, 4}, List.of("adg", "adh", "adi", "aeg", "aeh", "aei", "afg", "afh", "afi", "bdg", "bdh", "bdi", "beg", "beh", "bei", "bfg", "bfh", "bfi", "cdg", "cdh", "cdi", "ceg", "ceh", "cei", "cfg", "cfh", "cfi")),
+            Arguments.of(new int[] {3, 3}, List.of("dd", "de", "df", "ed", "ee", "ef", "fd", "fe", "ff")), Arguments.of(new int[] {8, 4}, List.of("tg", "th", "ti", "ug", "uh", "ui", "vg", "vh", "vi")), Arguments.of(new int[] {2, 0}, List.of("a ", "b ", "c ")),
+            Arguments.of(new int[] {9, 2}, List.of("wa", "wb", "wc", "xa", "xb", "xc", "ya", "yb", "yc", "za", "zb", "zc")), Arguments.of(new int[] {0}, List.of(" ")), Arguments.of(new int[] {1}, List.of("")), Arguments.of(new int[] {2}, List.of("a", "b", "c")),
+            Arguments.of(new int[] {1, 2, 0, 4}, List.of("a g", "a h", "a i", "b g", "b h", "b i", "c g", "c h", "c i")));
+    }
 
-        // ** Test 4 **
-        // Input: digits = "234"
-        // Output: ["adg", "adh", "adi", "aeg", "aeh", "aei", "afg", "afh", "afi",
-        // "bdg", "bdh", "bdi", "beg", "beh", "bei", "bfg", "bfh", "bfi", "cdg", "cdh",
-        // "cdi", "ceg", "ceh", "cei", "cfg", "cfh", "cfi"]
-        int[] numbers4 = {2, 3, 4};
-        List<String> output4 = Arrays.asList("adg", "adh", "adi", "aeg", "aeh", "aei", "afg", "afh", "afi", "bdg", "bdh", "bdi", "beg", "beh", "bei", "bfg", "bfh", "bfi", "cdg", "cdh", "cdi", "ceg", "ceh", "cei", "cfg", "cfh", "cfi");
-        assertTrue(LetterCombinationsOfPhoneNumber.printWords(numbers4, numbers4.length, 0, "").equals(output4));
+    private static Stream<Arguments> wrongInputs() {
+        return Stream.of(Arguments.of(new int[] {-1}), Arguments.of(new int[] {10}), Arguments.of(new int[] {2, 2, -1, 0}), Arguments.of(new int[] {0, 0, 0, 10}));
     }
 }