# Recursive Anagram

• 07-24-2007, 02:54 PM
zoe
Recursive Anagram
I am having trouble wrapping my head around the concept of recursion. I get how it is implemented, though I have trouble when asked to code anything using the technique. Here is my problem:

I need to write a recursive method that takes a string variable entered by a user and displays all anagrams of that word (i.e. entering cat would display "Cat, Cta, atC, aCt, tCa, taC"). I have been instructed that the method should take in two paramters, prefix and suffix, both strings. The whole word, the first time the method will be called, will be the suffix, while the prefix will be empty. Each recursive call will increment the prefix by one letter, decrement the suffix. I suppose the point is that the suffix gets smaller and smaller and when it reaches 1 letter in length, the recursion stops. Somehow the letters should be rearranged in every possible order, but I can't figure it out. Here is what I have so far:
Code:

```public static void anag(String prefix, String suffix) {         if (suffix.length()==1)             System.out.println(prefix+suffix);         else         {                        prefix=suffix.charAt(0)+prefix;                 for(int x=0; x<suffix.length(); x++)                 {                            suffix=suffix.substring(1);                                                                     suffix=suffix.charAt(suffix.length()-1)+suffix.substring(1);                         anag(prefix,suffix);                        }                }         }```
I don't know what to do in the slightest. I don't know how to approach it. Any tips? Disregard the code snippet if it is totally wrong. I was just trying my hand at incrementing and decrement the strings, possibly rearranging the letters, but it doesn't work very well at all.
Thanks
• 08-07-2007, 06:15 AM
fernando
Three things to remember when you are doing a recursive method.

The method should return a value type, and it should have a recursive case, and a non recursive case.

Although elegant, recursion can be a doozy to wrap your head around

The following is not necessarily correct, but should get you thinking on the right track.

Code:

```String anagram(String suffix, String prefix) { if (prefix == null) return; for (int i = 0; i < suffix.length() ; i++) { System.out.println(anagram(<mess with prefix suffix here>)); } }```