Note that there are some explanatory texts on larger screens.

plurals
  1. POWriting sequences program in Java using recursion
    primarykey
    data
    text
    <p>I've been tasked with a problem that finds all the subsequences for a string. </p> <p>For example, if the string is "bat" the subsequences returns [,b, ba, at, bt, t]</p> <p>Notice how it doesn't have all the permutations of the string since it has to go in order. The first string is an empty string and that's apparently requires by the instructions. </p> <p>Another example is the string "brat". The expected output for that would be [, a, at, b, ba, bat, br, bra, brat, brt, bt, r, ra, rat, rt, t]</p> <p>I've tried to write a program that would use recursion and give me the output but I've only gotten so far. I'm sure I understand recursion but I don't know how I would try to code this problem. </p> <p>This is what I have so far:</p> <pre><code>import java.util.ArrayList; public class Sequences { public static ArrayList&lt;String&gt; sequences(String s) { ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;(); return subsequences(s, list); } public static ArrayList&lt;String&gt; sequences(String s, ArrayList&lt;String&gt; list) { list.add(""); if (s.length() == 0) list.add(s); else { list.add(s); String temp = s.substring(0,1); String next = s.substring(1, s.length()); list.add(temp); sequences(next); } return list; } } </code></pre> <p>I also wrote a tester really quickly so I can test the problem since a tester wasn't provided to us: </p> <pre><code> public class tester { public static void main(String[] args) { System.out.println(Sequences.sequences("at")); } } </code></pre> <p>The output I'm getting is [, a] when I should have gotten [,a, at, t]</p> <p>Any help would be welcome!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload