Efficient search for permutations that contain sub-permutations via array operations?

后端 未结 3 879
时光说笑
时光说笑 2021-01-06 11:04

I have a set of integers, say S = {1,...,10}, and two matrices N and M, whose rows are some (but not necessarily all possible) permutations of elements from S of orders, say

3条回答
  •  囚心锁ツ
    2021-01-06 11:24

    How about this?

    n = size(N,1);
    m = size(M,1);
    p = size(N,2);
    pattern = (1:p).'; %'// will be used for checking if it's a subpermutation or not
    result = false(m,n); %// preallocate result, and initiallize to 0
    for k = 1:size(N,1) %// loop over columns of (transposed) N
        [~, loc] = ismember(M, N(k,:)); %// entries of M equal to a value of N(:,k)
        ind = find(sum(loc>0,2)==p); %// we need p matches per row of M
        t = reshape(nonzeros(loc(ind,:).'),p,[]); %'// for those rows, take matches
        ind2 = all(bsxfun(@eq,t,pattern)); %// ... see if they are in the right order
        result(ind(ind2),k) = true; %// ... and if so, take note in result matrix
    end
    

    The result matrix contains 1 at position r,s if the s-th row N is a sub-permutation of the r-th row of M. From this, your desired results are

    result1 = any(result,2);
    result2 = sum(result,1);
    

    Example:

    M =
         8     9     4     1    10
         6     5     2     7     8
         4     1     9     2    10
         3     4     5     1     2
    
    N =
         4     1     2
         4     9    10
         3     5     9
    

    give

    result =
         0     0     0
         0     0     0
         1     1     0
         1     0     0
    
    result1 =
         0
         0
         1
         1
    
    result2 =
         2     1     0
    

提交回复
热议问题