Comparing arrays of different sizes without any loop

前端 未结 2 1264
悲&欢浪女
悲&欢浪女 2021-01-25 07:18

The question goes like this:

Given two arrays, a & b (both with positive integers).

A special number is a number whi

2条回答
  •  悲&欢浪女
    2021-01-25 07:57

    I was holding off posting my solution because I correctly suspected that this question was a homework assignment. However, since the OP has accepted Jonas's answer, I might as well post mine.

    Code

    A combination of sum, length, any, and min does the trick:

    function out = stupidTutor(a, b)
    
    a        = sum(a, 1);           % if a is empty, replace it by a 1-by-0 matrix
    specials = a(a == 1:length(a)); % construct the vector of special numbers
    b        = sum(b, 1);           % if b is empty, replace it by a 1-by-0 matrix
    
    % some dyadic-product shenanigans
    A   = specials' * (b == b);
    B   = (specials == specials)' * b;
    ind = any(A == B, 1);
    
    temp = min(b(ind));         % temp is either a scalar, a 1-by-0 matrix, or []
    out  = sum(sum(temp, 2), 1); % trick to return 0 in case temp be 1-by-0 or []
    

    Tests

    %               a           b                 result
    stupidTutor([9 9 3 9]  , [3 4 5])       %       3  
    stupidTutor([9 9 3 9]  , [9 8])         %       0
    stupidTutor([9 9 9 9 5], [3 4 5 3])     %       5
    stupidTutor([9 9 3 9 5], [3 4 5 3])     %       3
    stupidTutor([9 9 3 9 5], [5 4 3 2 1])   %       3
    stupidTutor([9 9 3 9]  , [])            %       0
    stupidTutor([]         , [3 4 5])       %       0
    stupidTutor([]         , [])            %       0
    

提交回复
热议问题