0

I am trying to write a code in Java that would allow me to take a random String like "cat" and generate all the possible letter combinations, including shorter strings.

The answers offered on the other question marked as the duplicate (Generating all permutations of a given string) don't answer this question. None of the answers include the smaller words.

For Example: c, ca, ct, cat, cta, a, ac, at, act, atc, t, ta, tc, tac, tca. ( I think that's all of them)

I have seen several answers throughout SO, but all the ones I have found reuse letters. Like ccc, cca, cct, cac, caa, cat

This answer seems to be the closest All possible words, but it allows letters to be reused. I was thinking maybe I could just modify that code to do a check of whether the character was already used, but that becomes tough with words with repeated letters, i.e. cattail.

Any and all help would be appreciated. I'll post any code if it'll help, but the link above is pretty much as far as I've gotten.

Thanks

6
  • So something like generating all permutations of a set? Commented May 5, 2014 at 3:40
  • I think so, but without repeats Commented May 5, 2014 at 3:41
  • Take a look at this: Steinhaus–Johnson–Trotter algorithm Commented May 5, 2014 at 3:42
  • You can fairly easily remove duplicates by running the list through a HashSet, LinkedHashSet or TreeSet before printing. Commented May 5, 2014 at 14:17
  • I updated the title to include the requirements you stated, these requirements which are apparently not in the suggested duplicate. I'm voting to leave open. Commented May 5, 2014 at 14:18

1 Answer 1

0

Here you go!

public static void printAnagrams(String prefix, String word) { if (word.length() <= 1) { System.out.println(prefix + word); } else { for (int i = 0; i < word.length(); i++) { String cur = word.substring(i, i + 1); String before = word.substring(0, i); String after = word.substring(i + 1); printAnagrams(prefix + cur, before + after); } } } 

call it like printAnagrams("", "cat")

Sign up to request clarification or add additional context in comments.

3 Comments

This is almost perfect. I can't tell if it makes smaller words too though. Getting the word cat from catfish for example, or are all the answers the same length of the original word?
Yes, all generated anagrams are the same length as the original string.
I need the smaller words too, I'm afraid. I adjusted the original answer since I didn't make that clear earlier

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.