没有任何循环比较不同大小的阵列 [英] Comparing arrays of different sizes without any loop

查看:119
本文介绍了没有任何循环比较不同大小的阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是这样的:

由于两个数组, A &安培; B (均为正整数)。

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

A 特殊号码是一个数字,它 A(I)== I (其值等于索引)。

A special number is a number which a(i) == i (the value equals to the index).

您如何检查数组 B 包含一个值,该值特殊号码 >在。

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);

不起作用。

BTW:只能使用这些功能。排序的isEmpty所有,任何,查找,求和,最大值,最小值,长度。没有循环或条件!只允许使用的阵列。没有矩阵。不能用逻辑运算符,如:放;, |

谢谢!

推荐答案

我是持观望态度张贴我的解决方案,因为我correctly怀疑这个问题是一个家庭作业。然而,由于OP接​​受乔纳斯的回答,我还不如后我的。

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.

的组合,长度任何的伎俩:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆