我建議生成1到5的所有可能的組合,並刪除無效的組合。
代碼例如:
%generates all possible combinations from 1 to 5, where 1 is the first
%number
allCombs = perms(2:5);
allCombs = [ones(size(allCombs,1),1),allCombs];
%calclates rows in which the constraints for 1,4,5 holds
constraintsFor1 = union(findKAfterNRows(allCombs,2,1),findKAfterNRows(allCombs,3,1));
constraintsFor4 = union(findKAfterNRows(allCombs, 4,5),findKAfterNRows( allCombs, 4,3));
constraintsFor5 = union(findKAfterNRows(allCombs, 5,2),findKAfterNRows(allCombs, 5,4));
%calculates the valid rows
resultRows = intersect(constraintsFor1,constraintsFor4);
resultRows = intersect(resultRows,constraintsFor5);
%generates final output
outputMask = allCombs(resultRows,:);
凡findKAfterNRows是接收組合的矩陣的函數,並且兩個數 - k和n,並返回其中,k來Ñ後的行:
function [ validRows ] = findKAfterNRows(mat, k,n)
kMask = single(mat==k);
nMask = single(mat==n);
n = size(mat,2);
kernel = zeros(1,n);
kernel(1:floor(n/2)) = 1;
kMaskShiftLeft = conv2(kMask,kernel,'same');
validRows = find(sum(nMask==1 & kMaskShiftLeft==1,2)==1);
end
結果:
outputMask =
1 3 4 2 5
1 3 4 5 2
1 3 2 4 5
1 3 2 5 4
1 2 3 4 5
1 2 3 5 4
1 2 5 4 3
1 2 5 3 4
1 2 3 5 4是無效的,因爲5不能3後來,相同的1 3 2 4 5 4因爲能來AF ter 5或3,而不是2 ... –
@ aka.nice感謝您的編輯:)但我需要這兩個序列,雖然5不能在3之後但在那個序列2已經在那裏,所以我們可以添加5。我認爲排列不會讓我們這樣做。 –