Code
import java.util.Collections;
import java.util.ArrayList;
/**
This program tests the subset generator.
*/
public class SubsetGeneratorTester
{
public static void main(String[] args)
{
SubsetGenerator generator
= new SubsetGenerator("rum");
ArrayList<String> subsets = generator.getSubsets();
// Sort the result for checking
Collections.sort(subsets);
System.out.println(subsets);
System.out.println("Expected: [, m, r, rm, ru, rum, u, um]");
}
}
And
Code
import java.util.ArrayList;
/**
This class generates subsets of a string.
*/
public class SubsetGenerator
{
/**
Constructs a subset generator.
@param aWord the word to obtain subsets from
*/
....
public ArrayList<String> getSubsets()
{
....
// Form a simpler word by removing the first character
....
// Generate all subsets of the simpler word
....
// Add the removed character to the front of
// each subset of the simpler word, and
// also include the word without the removed character
....
// Return all subsets
....
}
....
}
Is my starter code. I sort of worked around it and have this:Code
import java.util.Collections;
import java.util.ArrayList;
/**
This program tests the subset generator.
*/
public class SubsetGeneratorTester
{
public static void main(String[] args)
{
SubsetGenerator generator
= new SubsetGenerator("rum");
String subsets = generator.nextGen();
// Sort the result for checking
System.out.println(subsets);
System.out.println("Expected: [, m, r, rm, ru, rum, u, um]");
}
}
Code
import java.util.*;
import java.io.*;
public class SubsetGenerator
{
private String subset;
private int current;
private SubsetGenerator tailGenerator;
boolean addedFirst;
public SubsetGenerator(String aSubset)
{
subset = aSubset;
addedFirst = subset.length() == 0;
if (subset.length() > 0)
tailGenerator = new SubsetGenerator(subset.substring(1));
}
public String nextGen()
{
if (subset.length() == 1)
{
current++;
return subset;
}
String r = subset.charAt(current) + tailGenerator.nextGen();
if (!tailGenerator.SubsetGen())
{
current++;
if (current < subset.length())
{
String tailString = subset.substring(0, current)
+ subset.substring(current + 1);
tailGenerator = new SubsetGenerator(tailString);
}
return r;
}
return "none";
}
public boolean SubsetGen()
{
return addedFirst || tailGenerator != null && tailGenerator.SubsetGen();
}
}
This doesnt work either. Can anyone help? Heres the actual question:Implement a SubsetGenerator that generates all subsets of the characters of a string. For example, the subsets of the characters of all string "rum" are the eight strings
"rum","ru","rm","r","um","u","m", and ""
Note that the subsets don't have to be substrings -- for example, "rm" isn't a substring of "rum".