Reputation: 29
I want to generate "subsets" of a string and print the output in a certain order. For example, "rum" and I expected the output to be [rum, ru, rm, r, um, u, m] My code is below and now my output is [rum, ru, rm, um, r, u, m]. How do I change my code to make it work?
import java.util.*;
public class SubstringGenerator {
String word;
public SubstringGenerator(String x) { word = x;}
public static void main(String[] args){
SubstringGenerator a = new SubstringGenerator("rum");
List b = a.subsets();
Collections.sort(b, Collections.reverseOrder(Comparator.comparing(String::length)));
System.out.println(b);
}
public List subsets(){
ArrayList<String> subsets = new ArrayList<String>();
int len = word.length();
for (int i = 0; i < Math.pow(2,len); i++){
String a = "";
for (int j = 0; j < len; j++){
if ((i & (int) (Math.pow(2,j))) > 0) a += word.charAt(j) + "";
}
subsets.add(a);
}
return subsets;
}
}
Upvotes: 0
Views: 420
Reputation: 155
I believe your method of arranging is keep them all, then remove the last letter, then remove the second last, then the last two, the third last, third last and last, last three, etc.
So what you did is arrange the arraylist elements by length. This won't work as r is shorter than um and therefore will go after.
What I did is arranged the Subsets as follows:
I created an binary number that represents which letters are being kept. The digit '1' meant the character in this position is kept, while '0' means it isn't. I repeated the process for ever possible iteration, starting at 111 down to 001.
I hope this helps please ask if you need further assistance.
import java.util.*;
import java.lang.Math;
public class SubstringGenerator {
String word;
public SubstringGenerator(String x) { word = x;}
public static void main(String[] args){
SubstringGenerator a = new SubstringGenerator("rum");
List b = a.subsets();
System.out.println(b);
}
public List subsets(){
ArrayList<String> subsets = new ArrayList<String>();
int len = word.length();
for (int i = (int)(Math.pow(2,len)-1.0); i >0; i--){
String a = "";
String b= Integer.toBinaryString(i);
while(b.length()!=word.length()) b="0"+b;
for(int j=0; j<b.length(); j++) if (b.charAt(j)=='1') a+=word.substring(j, j+1);
subsets.add(a);
}
return subsets;
}
}
Upvotes: 2