• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Permutations

 
Mike Stach
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21417
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic