Generate multiple sequences of numbers with unique values ​​for each index

I have a string with numbers 1:n. I want to add a second line also with numbers 1:n, but they must be in random order, satisfying as follows:

  • Both lines should not have the same number.
  • No combination of numbers occurs twice

For example, in the following

Row 1:  1  2  3  4  5  6  7 ...
Row 2:  3  6  15 8  13 12 7 ...  

the number 7 occurs in the same position on both lines 1 and 2 (namely, in position 7, thereby not satisfying rule 1)

and in the next

Row 1:  1  2  3  4  5  6  7 ...
Row 2:  3  7  15 8  13 12 2 ...

the combination 2 + 7 appears twice (in positions 2 and 7, thereby not satisfying rule 2).

It might have been possible, but unnecessarily laborious, to do it manually (at least to a reasonable number), but for this, MATLAB should have a pretty elegant solution.

+5
3

. , : , node 'b' node 'a', , node 'b ' node' a ' :

,

3 2 5 1 4

3 -> 2 -> 5 -> 1 -> 4, :

Row 1:  1 2 3 4 5
Row 2:  4 5 2 3 1

.

? , , . 7 , 3 , 4 ? / ?

+1

. randperm, .

x = [1  2  3  4  5  6  7];
y = randperm(x);

, . , ..
0,3 , , , 10/3 , . .

.

Edit

> 2, . ,   , , . , .

+2

randperm , . p, , , any(p==1:n). , 2, any(p(p)==1:n).

, p of 1:n, :

p=[];
while (isempty(p))
    p=randperm(n);
    if any(p==1:n), p=[]; 
    elseif any(p(p)==1:n), p=[]; 
    end
end

Surrounding this with the contour forand for each iteration count of the cycle while, it seems that on average it is necessary to generate permutations 4.5for each "real" one (and 6.2if three cycles of length three are not allowed). Very interesting.

+1
source

All Articles