Comparing arrays of different sizes without any loop

前端 未结 2 1261
悲&欢浪女
悲&欢浪女 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:54

    Well, turns out there might be a way after all :). We make use of the fact that the numbers have to be strictly positive to be special numbers at all.

    %# in case we need to handle empty inputs: replace empty input with 0 or 1, respectively.
    a = sum(a(:)',1);
    bIsEmpty = isempty(b);
    b = sum(b(:)',1); b = max(b,1);
    
    specialNumber = find(a==1:length(a));
    
    maxAB = max(max(a), max(b));
    
    %# "zeros()"
    bigVectorForComparisonA = (1:maxAB)*0;
    bigVectorForComparisonB = (1:maxAB)*0;
    
    bigVectorForComparisonA(specialNumber) = 1;
    bigVectorForComparisonB(b) = 1;
    
    %# instead of &, we add. Find only the smallest match
    specialNumberInB = find(bigVectorForComparisonA + bigVectorForComparisonB == 2,1,'first');
    
    out = sum(specialNumberInB) * ~bIsEmpty; %# sum([]) = 0
    

    For a slightly prettier solution that assumes up to 1 special number in a

    specialNumber = min(find(a==(1:length(a)));
    
    out = any(b==specialNumber)*sum(specialNumber);
    

提交回复
热议问题