Repository: TheAlgorithms/Java
Pull request #5408 (2024-08-26 21:41:09)

refactor: `ReturnSubsequence`
Class cleanup.
Readability improvements.
Added 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/5408?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
All modified and coverable lines are covered by tests :white_check_mark:
> Project coverage is 48.95%. Comparing base [(`c5b73ec`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/c5b73ec742d0522d65331ee02a143f54041845ed?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`3750ee7`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/3750ee7830ec312e47a9c21d747085a050e50e95?dropdown=coverage&el=desc&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    #5408      +/-   ##
============================================
+ Coverage     48.85%   48.95%   +0.09%     
- Complexity     3039     3041       +2     
============================================
  Files           524      524              
  Lines         15256    15245      -11     
  Branches       2900     2899       -1     
============================================
+ Hits           7454     7463       +9     
+ Misses         7494     7474      -20     
  Partials        308      308              
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5408?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/others/ReturnSubsequence.java b/src/main/java/com/thealgorithms/others/ReturnSubsequence.java
index ef376c47..7ef660ce 100644
--- a/src/main/java/com/thealgorithms/others/ReturnSubsequence.java
+++ b/src/main/java/com/thealgorithms/others/ReturnSubsequence.java
@@ -1,46 +1,37 @@
 package com.thealgorithms.others;
 
-import java.util.Scanner;
-
+/**
+ * Class for generating all subsequences of a given string.
+ */
 public final class ReturnSubsequence {
     private ReturnSubsequence() {
     }
 
-    public static void main(String[] args) {
-        System.out.println("Enter String: ");
-        Scanner s = new Scanner(System.in);
-        String givenString = s.next(); // given string
-        String[] subsequence = returnSubsequence(givenString); // calling returnSubsequence() function
-        System.out.println("Subsequences : ");
-        // print the given array of subsequences
-        for (int i = 0; i < subsequence.length; i++) {
-            System.out.println(subsequence[i]);
-        }
-        s.close();
-    }
-
     /**
-     * @param givenString
-     * @return subsequence
+     * Generates all subsequences of the given string.
+     *
+     * @param input The input string.
+     * @return An array of subsequences.
      */
-    private static String[] returnSubsequence(String givenString) {
-        if (givenString.length() == 0) { // in it // If string is empty we will create an array of
-                                         // size=1 and insert "" (Empty string)
-            String[] ans = new String[1];
-            ans[0] = "";
-            return ans;
+    public static String[] getSubsequences(String input) {
+        if (input.isEmpty()) {
+            return new String[] {""}; // Return array with an empty string if input is empty
         }
-        String[] smallAns = returnSubsequence(givenString.substring(1)); // recursive call to get subsequences of substring starting from index
-        // position=1
 
-        String[] ans = new String[2 * smallAns.length]; // Our answer will be an array off string of size=2*smallAns
-        System.arraycopy(smallAns, 0, ans, 0, smallAns.length);
+        // Recursively find subsequences of the substring (excluding the first character)
+        String[] smallerSubsequences = getSubsequences(input.substring(1));
 
-        for (int k = 0; k < smallAns.length; k++) {
-            ans[k + smallAns.length] = givenString.charAt(0) + smallAns[k]; // Insert character at index=0 of the given
-                                                                            // substring in front of every string
-            // in smallAns
+        // Create an array to hold the final subsequences, double the size of smallerSubsequences
+        String[] result = new String[2 * smallerSubsequences.length];
+
+        // Copy the smaller subsequences directly to the result array
+        System.arraycopy(smallerSubsequences, 0, result, 0, smallerSubsequences.length);
+
+        // Prepend the first character of the input string to each of the smaller subsequences
+        for (int i = 0; i < smallerSubsequences.length; i++) {
+            result[i + smallerSubsequences.length] = input.charAt(0) + smallerSubsequences[i];
         }
-        return ans;
+
+        return result;
     }
 }


Test patch:
diff --git a/src/test/java/com/thealgorithms/others/ReturnSubsequenceTest.java b/src/test/java/com/thealgorithms/others/ReturnSubsequenceTest.java
new file mode 100644
index 00000000..0ae30c48
--- /dev/null
+++ b/src/test/java/com/thealgorithms/others/ReturnSubsequenceTest.java
@@ -0,0 +1,23 @@
+package com.thealgorithms.others;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+
+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;
+
+class ReturnSubsequenceTest {
+
+    @ParameterizedTest
+    @MethodSource("provideTestCases")
+    void testSubsequences(String input, String[] expected) {
+        String[] actual = ReturnSubsequence.getSubsequences(input);
+        assertArrayEquals(expected, actual);
+    }
+
+    static Stream<Arguments> provideTestCases() {
+        return Stream.of(Arguments.of("", new String[] {""}), Arguments.of("a", new String[] {"", "a"}), Arguments.of("ab", new String[] {"", "b", "a", "ab"}), Arguments.of("abc", new String[] {"", "c", "b", "bc", "a", "ac", "ab", "abc"}),
+            Arguments.of("aab", new String[] {"", "b", "a", "ab", "a", "ab", "aa", "aab"}));
+    }
+}