1

I have five numbers:

1,2,3,4,5

. I want to order these numbers with all the combination possibilities:

12345

12354

12435

12534...

Is there an easy way to do it without listing all the combination possibilities one by one? Maybe I could make a program to do it? I want to know a fast way to calculate, and eventually get the whole list.

Thanks!

  • Do you mean you want to calculate the position of a particular permutation when all are listed in some given order (say, lexicographical order)? Or do you want a list of all permutations? – M. Vinay Jun 04 '14 at 04:12
  • I want to know a fast way to calculate, and eventually get the whole list. – ʇolɐǝz ǝɥʇ qoq Jun 04 '14 at 04:19

2 Answers2

2

Hint: The number 54321 is in the 120th place.

It is also in the $ (5-1) \times 4! + (4-1) \times 3! + (3-1) \times 2! + (2-1) \times 1! + (1-1) \times 0! + 1$ place.

The number 12345 is in the 1st place.

It is also in the $(1-1) \times 4! + (2-2) \times 3! + (3-3) \times 2! + (4-4) \times 1! + (5-5) \times 0! + 1$ place.

Calvin Lin
  • 68,864
1

Here's a recursive algorithm for you

def generate_permutations(sequence):
    if lengthof(sequence)==1:
        return sequence
    else if lengthof(sequence)>1:
        for item in sequence:
            return item + generate_permuations(sequence - item)

Here's how it works. If the sequence is just one item long, the only permuation is itself. Else if it's longer, for each item in the sequence, place it at the beginning and permute the rest. It's easy to prove mathematically that this will produce all the sequences in lexicographic order. Here's python code for it.

sayantankhan
  • 2,397