我有一个使用 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
感谢您的回答,我曾想过类似的事情,我将验证它在计算复杂度方面的性能,因为我将生成 10,000 到 100,000 个排列的矩阵。