I want to randomly generate a permutation P of the first n natural numbers, and it has to satisfy that P[i] != i for every i<n.
How can I do it efficiently?
The first method I came up with is just to randomly select legal numbers for each position iteratively. However I found it doesn't seem to guarantee the randomness.
For example in the case of 4 numbers, if I (randomly) choose 2,3 for first two numbers, then the configuration for the last two numbers could be either 0,1 or 1,0. If I happen to choose say 1,2 for the first two, then the only available option left is 3,0 since the last bit can't be 3. So it seems the probability of 1,2,3,0 is twice as high as 2,3,0,1, right?
Another thing to do is to randomly generate a permutation and reject if it doesn't satisfy the condition, but the time complexity for this can't be guaranteed.