posted 15 years ago
I've written one before as a recursive function. If i recall correctly, you pass in a string. if the length of the string is 1, you add it to a collection and return that. if the length is greater than one, you strip of one character and pass that shortened string into the method (thus the recursion). Once you get back the collection of permutations of the shorter string, you insert the one stripped off character at every position in each string in the collection.
so... if you pass in "abc", you'd strip off the 'a', and pass "bc" into the method. you'd then strip off the 'b', and pass the string "c" into the method. this has a length of 1, so you'd insert that into a collection, and return it.
you now back in the iteration where you stripped off the 'b'. So, read the first string in the returned collection, and loop through inserting in the 'b' in every position. This would generate "bc" and "cb". Both of these strings are inserted into a collection, and since there are no more in the collection this method got from it's call, we pass the newly generated one up to the 'a' version.
You'd read the first string, and insert in the 'a' in every possible position, giving "abc", "bac" and "bca". You then read the next string of "cb", and insert the character to give you "acb", "cab", and finally "cba".
It's kind of hard to explain, but it worked.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors