java - Explain how this permutation works -
i searched code permutation in java:
public class mainclass { public static void main(string args[]) { permutestring("", "string"); } public static void permutestring(string beginningstring, string endingstring) { if (endingstring.length() <= 1) system.out.println(beginningstring + endingstring); else (int = 0; < endingstring.length(); i++) { try { string newstring = endingstring.substring(0, i) + endingstring.substring(i + 1); permutestring(beginningstring + endingstring.charat(i), newstring); } catch (stringindexoutofboundsexception exception) { exception.printstacktrace(); } } } }
i can't understand though know basic code. want explain me make clearer. thank guys
one can construct permutation, picking items bag repeatedly , constructing sequence. string, bag collection of characters. can use string
represent this.
if want construct random permutated string, first if bag empty. in above code, bag endingstring
, emptiness check done with:
if (endingstring.length() <= 1) system.out.println(beginningstring + endingstring);
as can see check not whether bag empty: moment string has 1 character (one element), evidently pick one. pick , print after sequence we've constructed.
problem: problem approach if want list permutations of empty string (there one: empty string), 1 errors.
now need iterative case. remember beginningstring
stores sequence we've constructed till , endingstring
stores list of characters still can pick from. way pick select valid index i
in endingstring
. character @ index picked.
we update sequence (beginningstring
appending character placed @ i
, thus:
beginningstring + endingstring.charat(i)
in order update bag, means bag contains characters before index, , ones after index. formalized as:
string newstring = endingstring.substring(0, i) + endingstring.substring(i + 1);
newstring
here new bag. can recursive call pick next item bag. given index i
, in order pick , call recursively, code reads:
string newstring = endingstring.substring(0, i) + endingstring.substring(i + 1); permutestring(beginningstring + endingstring.charat(i), newstring);
now since wish enumerate on all possible permutations, loop on possible indices i
. since recursively consequence, enumerate permutations.
Comments
Post a Comment