QA0007
Solution to Mathworks Cody problem 16: Given a vector string of integers, extract all numbers next to all vector nulls.
LINK TO QUESTION https://uk.mathworks.com/matlabcentral/cody/groups/2/problems/16
problem posted by Greg Wilson gvwilson@third-bit.com
clear all;close all;clc
%% generate random x
N=12; % define length vector x
n10=2; % make sure at least n0 zeros in vector
n20=6; % define roof amount zeros in x
N0=randi([n10 n20],1,1); % define amount zeros in x
disp([num2str(N0) ' zeros'])
x1=randi([-9 9],1,N-N0)
x=[]
N1=N-N0
N01=N0
while N1+N01>0
if ~randi([0 1],1,1) && N01>0 % decide 0 or ~0
x=[x 0]; % append 0
N01=N01-1;
end
if ~randi([0 1],1,1) && N1>0
x=[x x1(1)];
x1(1)=[];
N1=N1-1;
end
end
x % check
%% find largest number next to null
L=[]
nL0=find(x==0)
for k=1:1:numel(nL0)
if (nL0(k)>1 && ...
nL0(k)<N && ...
x(nL0(k)+1))
L=[L x(nL0(k)+1)];
end
if (nL0(k)>1 && ...
nL0(k)<N && ...
x(nL0(k)-1))
L=[L x(nL0(k)-1)];
end
if (~x(1)==1 && x(2))
L=[L x(2)];
end
if (~x(N) && x(N-1))
L=[L x(N-1)];
end
end
max(L)
%% comments on a few other answers
%%
% Naixin mu answer doesn't work for
% x=[0 9 0 6 0 5 6 8 5 2 5]
% should return 9 but returns 6
x2=[-inf,x,-inf];
a=x(find(x2==0)-1);
b=x(find(x2==0)+1);
y=max([a,b])
%%
% Haoyu Dai answer doesn't work for
% x=[0 9 0 6 0 5 6 8 5 2 5]
% should return 9 but returns a vector with 5 elements
% one of them is the correct answer, but when asked for max
% there's only one possible answer.
y = [];
a=[];
k=1;
L2=length(x);
for i=1:L2
if x(i)==0
if i==1
a(k)=x(i+1);
k=k+1;
elseif i==L2
a(k)=x(i-1);
k=k+1;
else
a(k)=x(i-1);
a(k+1)=x(i+1);
k=k+2;
end
end
end
[y,index]=max(a);
%%
% Jianghao Su answer doesn't work for
% x= [0 -2 -4 0 -7 -2 0 0 -2 -7 0]
% it returns 0
x=[-inf,x,-inf];
zeroindex=find(~x);
zeroindexl=zeroindex-1;
zeroindexr=zeroindex+1;
y=max([x(zeroindexl),x(zeroindexr)])
%%
% Quinhua Ye answer doesn't work
% because for % x= [0 -2 -4 0 -7 -2 0 0 -2 -7 0]
% it returns error: index exceeds array elements number (12)
% attempting to index beyond available indices.
x2 = [min(x(x~=0)),x,min(x(x~=0))];
indx = find(x2 == 0);
y = max([x(indx-1),x(indx+1)]);