View Single Post
  #1 (permalink)  
Old 07-24-2007, 04:54 PM
zoe zoe is offline
Member
 
Join Date: Jul 2007
Posts: 40
zoe is on a distinguished road
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
Reply With Quote
Sponsored Links