如何进行有限制的排列?

How to do a permutation with restrictions?

我有一个使用 Matlab 的向量,其值是从 1 到 18,考虑到某些数字不能放在一起,我需要对这些值执行排列。例如:

vector = [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18]

在我的条件下,以下数字不能在一起:

1 and 7
1 and 8
1 and 17
1 and 18
2 and 6
2 and 7
2 and 8
2 and 17
2 and 18

所以一个有效的排列可以是:

[1 2 4 3 5 6 7 8 9 10 11 12 13 14 15 17 16 18]

无效排列可能是:

[1 7 4 3 5 6 2 8 9 10 11 12 13 14 15 17 16 18] 1 and 7 together
[1 8 4 3 5 6 2 7 9 10 11 12 13 14 15 17 16 18] 1 and 8 together
[1 17 4 3 5 6 2 8 9 10 11 12 13 14 15 7 16 18] 1 and 17 together

这些条件必须适用于矢量的任何位置。 我不知道该怎么做,如果有人能给我一些想法,我将不胜感激。

考虑到之前的评论,我的代码生成了向量的随机排列,并检查所有这些组合是否不在排列中。如果找到某些条件,则会生成新的排列:

vector = [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18];

not_valid = 1;
while not_valid == 1
    randpermutation = vector(randperm(18))

    not_valid = 0;
    for i = 1:length(randpermutation)-1
        if randpermutation(i) == 1 && randpermutation(i+1) == 7 || randpermutation(i) == 7 && randpermutation(i+1) == 1
            not_valid = 1;
        end
        if randpermutation(i) == 1 && randpermutation(i+1) == 8 || randpermutation(i) == 8 && randpermutation(i+1) == 1
            not_valid = 1;
        end
        if randpermutation(i) == 1 && randpermutation(i+1) == 17 || randpermutation(i) == 17 && randpermutation(i+1) == 1
            not_valid = 1;
        end
        if randpermutation(i) == 1 && randpermutation(i+1) == 18 || randpermutation(i) == 18 && randpermutation(i+1) == 1
            not_valid = 1;
        end
        if randpermutation(i) == 2 && randpermutation(i+1) == 7 || randpermutation(i) == 7 && randpermutation(i+1) == 2
            not_valid = 1;
        end
        if randpermutation(i) == 2 && randpermutation(i+1) == 8 || randpermutation(i) == 8 && randpermutation(i+1) == 2
            not_valid = 1;
        end
        if randpermutation(i) == 2 && randpermutation(i+1) == 17 || randpermutation(i) == 17 && randpermutation(i+1) == 2
            not_valid = 1;
        end
        if randpermutation(i) == 2 && randpermutation(i+1) == 18 || randpermutation(i) == 18 && randpermutation(i+1) == 2
            not_valid = 1;
        end
        if randpermutation(i) == 2 && randpermutation(i+1) == 6 || randpermutation(i) == 6 && randpermutation(i+1) == 2
            not_valid = 1;
        end
    end
end