我有一个使用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