Note that there are some explanatory texts on larger screens.

plurals
  1. POGenerating all subsets of characters in a string using recursion, JAVA
    text
    copied!<p>Forgive me if I mess this up, this is my first question. I've been working on this problem for hours. It is supposed to generate all subsets of characters (<strong><em>not necessarily substrings</em></strong>) in a string, using recursion. I commented it a lot so you could see my thinking and hopefully tell me where I'm going wrong. I'm using Eclipse as an IDE if that makes any difference.</p> <pre><code> import java.util.ArrayList; //Generates subsets of a string public class SubsetGenerator { private String original; private String remaining; private ArrayList&lt;String&gt; subsets; //Constructs a subset generator //@param input string to have subsets generated public SubsetGenerator(String input) { original = input; remaining = original; subsets = new ArrayList&lt;String&gt;(); } public void printSubsets() { System.out.print(subsets); } //gets subsets public void generateSubsets() { //if the string is empty, it has no subsets if(remaining.length() == 1) { subsets.add(remaining); return; } else { //remove the first character and hold onto it String removed = remaining.substring(0,1); remaining = remaining.substring(1); //recursion. Eventually it should add the last character in the string to the ArrayList and return generateSubsets(); //Take each element that is in the ArrayList, add the removed character to it, add this back to the list for (int i = 0; i &lt; subsets.size(); i++) { String temp = removed + subsets.get(i); subsets.add(temp); } subsets.add(removed);//add the removed character by itself return; } } } </code></pre> <p>These are the errors I'm getting:</p> <pre><code>Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOfRange(Arrays.java:3221) at java.lang.String.&lt;init&gt;(String.java:233) at java.lang.StringBuilder.toString(StringBuilder.java:447) at SubsetGenerator.generateSubsets(SubsetGenerator.java:41) at SubsetGenerator.generateSubsets(SubsetGenerator.java:37) at SubsetGenerator.generateSubsets(SubsetGenerator.java:37) at SubsetGenerator.generateSubsets(SubsetGenerator.java:37) at SubsetGeneratorTester.main(SubsetGeneratorTester.java:7) </code></pre> <p>I've tested it with this code:</p> <pre><code>public class SubsetGeneratorTester { public static void main(String[] args) { SubsetGenerator s = new SubsetGenerator("world"); s.generateSubsets(); s.printSubsets(); } } </code></pre>
 

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