在没有任何循环的情况下比较不同大小的数组 [英] Comparing arrays of different sizes without any loop
问题描述
问题是这样的:
给定两个数组,a
&b
(均为正整数).
Given two arrays, a
& b
(both with positive integers).
special number
是 a(i) == i
的数字(值等于索引).
A special number
is a number which a(i) == i
(the value equals to the index).
如何检查数组 b
是否包含 a
的 特殊数字
的值.
How can you check if array b
contains a value which is a special number
of a
.
例如:a = [9 9 3 9]
、b = [3 4 5]
.输出将是 3
.如果 b
或 a
为空,则输出为 0
.如果b
包含多个特殊数字
,只会显示最小的一个.
For example: a = [9 9 3 9]
, b = [3 4 5]
. Output will be 3
. If b
or a
are empty, output is 0
. If b
contains several special number
, only the smallest one will be shown.
这是我到目前为止所做的事情,无法从这里取得进展..
This is what I have managed to do by far, can't progress from here..
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);
不工作.
顺便说一句:只能使用这些功能:.排序、 isempty 、 all 、 any 、 find 、 sum 、 max 、 min 、 长度.没有循环或条件!只允许使用数组.没有矩阵.不能使用 &、|
谢谢!
推荐答案
我推迟发布我的解决方案,因为我 正确怀疑这个问题是家庭作业.但是,由于 OP 已接受 Jonas 的回答,我不妨发布我的.
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.
sum
、length
、any
和 min
的组合可以解决问题:
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 []
测试
% 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
这篇关于在没有任何循环的情况下比较不同大小的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!