# Permutations

Mike Stach

Greenhorn

Posts: 8

posted 7 years ago

- 0

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.

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.

posted 7 years ago

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.

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 ]

- 0

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 ]

Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters? |