0

In how many ways can you arrange a sequence of 'n' (1 to n) numbers such that no number occurs at the index represent by its value?

For eg

1 can not be at first position
2 can not be at second position
.
.
n can not be at nth position

Please give a general solution. Also solve it for n=6. Its not a homework.

Shashwat
  • 2,538
  • 7
  • 37
  • 56
  • 4
    If it walks like a duck, and talks like a duck... are you *sure* it's not homework? – Eric J. Jul 18 '12 at 05:16
  • The question of how to generate derangements programmatically has been [dealt with previously here](http://stackoverflow.com/q/8369941/487781). The formula to count them is strictly speaking a math topic (and see my answer linking to such a question at MathSE). – hardmath Jul 18 '12 at 14:42

3 Answers3

2

You want fixed point free permutations, also known as derangements. The formula for their number is slightly more complicated than for the number of permutations that may have fixed points.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
  • Very slightly, the nearest integer to n!/e. The Wikipedia article doesn't explain this clearly, though it notes the fraction of derangements converges to 1/e and gives `floor((n!/e) + (1/2))` as an exact expression. – hardmath Jul 18 '12 at 14:31
2

Let P(n) be the number of such arrangements for n numbers.

For 123456....n
Cases are of the form

2*****
3*****
4*****
5*****
.
.
n*****

Now 1 can be anywhere at the rest (n-1) positions.
If 1 is put at the position of the number replacing it...

21****
3*1***
4**1**
.
.
n****1

then first and the replaced numbers are fixed.
Then total cases = (n-1) * P(n-2)

Else if
1 is also restricted not to be at a particular position (positions in above cases)
Then total cases = (n-1) * P(n-1)

So

P(n) = (P(n-1) + P(n-2)) * (n-1)

with P(1) = 0

and P(2) = 1

Shashwat
  • 2,538
  • 7
  • 37
  • 56
1

The number of derangements (fixed point free permutations) of n things is round(n!/e) where e is the base of natural logarithms. Here round means nearest integer function. This is described in the Wikipedia article, but in a manner that could stand clarification.

For n = 6 one easily calculates there are round(264.87...) = 265 derangements.

In effect you've asked a frequently covered question from MathSE.

Community
  • 1
  • 1
hardmath
  • 8,753
  • 2
  • 37
  • 65