Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm for generating different orders

I am trying to write a simple algorithm that generates different sets

(c b a) (c a b) (b a c) (b c a) (a c b) from (a b c)

by doing two operations:

exchange first and second elements of input (a b c) , So I get (b a c)

then shift first element to last = > input is (b a c), output is (a c b)

so final output of this procedure is (a c b).

Of course, this method only generates a c b and a b c. I was wondering if using these two operations (perhaps using 2 exchange in a row and then a shift, or any variation) is enough to produce all different orderings?

I would like to come up with a simple algorithm, not using > < or + , just by repeatedly exchanging certain positions (for example always exchanging positions 1 and 2) and always shifting certain positions (for example shift 1st element to last).

like image 693
Abramo K. Avatar asked Mar 08 '12 21:03

Abramo K.


People also ask

What is combination algorithm?

In this method, we'll pick an element then find a combination of r-1 elements. As we're picking an element from the rest of the element, we are doing recursively, and that's why it's called fixed element and recursion.

What is a permutation algorithm?

This algorithm is based on swapping elements to generate the permutations. It produces every possible permutation of these elements exactly once. This method is a systematic algorithm, which at each step chooses a pair of elements to switch in order to generate new permutations.

How does Heap's algorithm work?

Heap's algorithm is used to generate all permutations of n objects. The idea is to generate each permutation from the previous permutation by choosing a pair of elements to interchange, without disturbing the other n-2 elements. Following is the illustration of generating all the permutations of n given numbers.


1 Answers

Note that the shift operation (move the first element to the end) is equivalent to allowing an exchange (swap) of any adjacent pair: you simply shift until you get to the pair you want to swap, and then swap the elements.

So your question is essentially equivalent to the following question: Is it possible to generate every permutation using only adjacent-pair swap. And if it is, is there an algorithm to do that.

The answer is yes (to both questions). One of the algorithms to do that is called "The Johnson–Trotter algorithm" and you can find it on Wikipedia.

like image 124
Omri Barel Avatar answered Oct 19 '22 09:10

Omri Barel