File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Permutations Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Permutations" Watch "Permutations" New topic
Author

Permutations

Mike Stach
Greenhorn

Joined: Oct 26, 2008
Posts: 8
Lets say we have collection of 3 objects and we wish to find permutations amongst them. I know there are elegant ways to write this recursively but is there a way to improve the below iterative version?



If I increase or decrease the collection size from 3, I do not want code duplication. I want to come up with a generic way of iteratively finding permutations regardless of the size of collection.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18760
    
  40

Lets say we have collection of 3 objects and we wish to find permutations amongst them. I know there are elegant ways to write this recursively but is there a way to improve the below iterative version?


With only 3 objects, there are only 6 permutations -- 123, 132, 213, 231, 312, and 321. Instead of having a loop within a loop within a loop, you can actually hardwire the six answers.

If I increase or decrease the collection size from 3, I do not want code duplication. I want to come up with a generic way of iteratively finding permutations regardless of the size of collection.


Most algorithm books show how to do this, using a stack to determine what was done -- ie. keeping track of the current state of things. However, these same books, after doing this, comes to the conclusion that all they are doing is simulating recursion... In other words, recursion is the solution. You can use recursion. Or you can use loops, and stack data structures to simulate recursion.

Henry
[ November 06, 2008: Message edited by: Henry Wong ]

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Permutations