I wrote a recursive method that gets all possible character combinations from the characters in a string. I also have a method to access it and return a list of the combos:
public static void uns(String word, StringBuilder s, List combos)
{
for(char c: word.toCharArray())
{
s.append(c);
if(word.length() != 1)
{
uns(removeChar(word, c),s,combos);
}
else
{
combos.add(s.toString());
}
s.deleteCharAt(s.toString().length()-1);
}
}
public static List getCombinations(String word)
{
List<String> combinations = new ArrayList<String>();
uns(word,new StringBuilder(),combinations);
return combinations;
}
public static String removeChar(String s, char c)
{
int index = s.indexOf(c);
return s.substring(0,index)+s.substring(index+1);
}
When testing it in Java, it ran with no flaws. For some reason, when I use it in Android, the list is populated with the correct number of elements, but every element is the same. For instance, for the word "here", it returns a list filled with "eerh".
This is a very weird glitch (definitely reproducible) and you may want to file a bug report on this.
However, here is a temporary workaround; instead of using .toString()
, which appears to somehow reuse the reference (even if I do .substring(0)
with it), so all of them get updated; if you print out the list after each iteration, you'll see what I mean.
Here is my hacky/inefficient solution. Change:
combos.add(s.toString());
... to:
combos.add(s + "");
This effectively clones the string properly into the array, so that they are not manipulated:
02-17 19:33:48.605: I/System.out(6502): [Combos]: [here, heer, hree, hree, here, heer, ehre, eher, erhe, ereh, eehr, eerh, rhee, rhee, rehe, reeh, rehe, reeh, ehre, eher, erhe, ereh, eehr, eerh]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With