Results 1 to 3 of 3
 03172013, 01:49 AM #1Senior Member
 Join Date
 Nov 2011
 Posts
 165
 Rep Power
 9
Permutation of String ( Problem in understandin Code )
Please consider the following code for finding the permutation of a string:
Java Code:public static ArrayList<String> permutations(String str) { ArrayList<String> result = new ArrayList<String>(); int length = str.length(); switch(length) { case 0: break; case 1: result.add(str); break; case 2: result.add(str); String rstr = new StringBuffer(str).reverse().toString(); result.add(rstr); break; default: for (int i = 0; i < length; i++) { String remaining = new StringBuffer(str).deleteCharAt(i).toString(); for (String sub_permutation : permutations(remaining)) { String s = str.charAt(i) + sub_permutation; result.add(s); } } break; } return result; }
If we consider the case where str = abc. Then I can understand that since the length is 3, the program control will go
to default setting where , String variable "remaining" will hold "bc" part of String "abc" after the initial character is removed.
If we consider the line "Java Code:for (String sub_permutation : permutations(remaining))
from the string abc, the case 2 condition will be matched (becauseJava Code:permutation(bc)
Java Code:result.add(rstr)
Can anyone explain me what I'm not understanding in the code?
 03172013, 02:36 AM #2Senior Member
 Join Date
 Jan 2013
 Location
 Northern Virginia, United States
 Posts
 6,226
 Rep Power
 14
Re: Permutation of String ( Problem in understandin Code )
Your analysis of what is going on seems correct to me. Therefore, I am not understanding what it is you are looking for. Did you write this yourself or are you just trying to understand someone else's algorithm?
Regards,
JimLast edited by jim829; 03172013 at 02:56 AM. Reason: followup question
The Java^{TM} Tutorials  SSCCE  Java Naming Conventions
Poor planning on your part does not constitute an emergency on my part
 03172013, 03:41 AM #3Senior Member
 Join Date
 Oct 2012
 Posts
 108
 Rep Power
 0
Re: Permutation of String ( Problem in understandin Code )
Java Code:for (String sub_permutation : permutations(remaining)) // Reads: FOR EACH String sub_permutation IN permutations(remaining) DO
as the result of permutations("bc") is the ArrayList<String> containing "bc" and "cb"
Similar Threads

Loops and recursion: get every permutation of ArrayList elements, order matters
By b1707107 in forum New To JavaReplies: 5Last Post: 01222013, 07:13 PM 
random array permutation
By jwl in forum New To JavaReplies: 1Last Post: 11152012, 08:01 PM 
Need a help in two dimentaional permutation
By venk123 in forum New To JavaReplies: 7Last Post: 08062011, 01:28 AM 
Permutation
By Claymz in forum New To JavaReplies: 4Last Post: 06012011, 02:27 PM 
Mapping of variables to values (permutation with repetition?)
By electra in forum Advanced JavaReplies: 3Last Post: 08242009, 07:39 PM
Bookmarks