比较不同大小的数组,没有任何循环

时间:2014-11-18 23:57:19

标签: arrays matlab compare

问题是这样的:

给定两个数组,a& b(均为正整数)。

special numbera(i) == i(值等于索引)的数字。

如何检查数组b是否包含special number a的值。

例如:a = [9 9 3 9]b = [3 4 5]。输出将为3。如果ba为空,则输出为0。如果b包含多个special number,则只显示最小的一个。

这是我迄今为止所做的,不能从这里开始......

a = input('Please enter the array a : ');
b = input('Please enter the array b : ');

indexedArray = 1:length(a);
c = a-indexedArray;
t = find(c==0);   
p = find(t==b);

不起作用。

BTW:只能使用这些功能:。 sort,isempty,all,any,find,sum,max,min,length。没有循环或条件!仅允许使用数组。没有矩阵。无法使用&,|

等逻辑运算符

谢谢!

2 个答案:

答案 0 :(得分:2)

嗯,事实证明可能有一种方法:)。我们利用这样一个事实,即数字必须严格为正数,才能成为特殊数字。

%# 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

对于一个稍微漂亮的解决方案,在a

中假定最多1个特殊数字
specialNumber = min(find(a==(1:length(a)));

out = any(b==specialNumber)*sum(specialNumber);

答案 1 :(得分:2)

我暂时没有发布我的解决方案,因为我correctly怀疑这个问题是家庭作业。但是,由于OP已接受Jonas's answer,我不妨发布我的。

代码

sumlengthanymin的组合可以解决问题:

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 []

测试

%               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