function [c] = nextinteger(v)
c=0;
a =0;
h=[0];
for i= 1:length(v)
if v(i)>0
h=v;
if h(i+1)>h(i)
a = h(i);
c=a+1;
end
end
end
end
I have to "Write a function nextinteger(v)
which takes as input a vector v
and as output returns the smallest positive integer which does not appear in v
."
At the moment I cannot seem to find a solution and the code above is as far as I have got to the solution. Can someone tell me what I need to consider and what I need to fix to get closer to my solution
Example of desired outcome: If the input is
[1, 2, 3]
, the output would be
4
If the input is
[4, 0, 1, -10],
the output would be
2
Example Input
v=[10 0 1 -1 3 4 5];
n=length(v); % length of input
tmp=1:n; % possible integer numbers
for k=1:n % loop over vector
comp_value=v(k);
for r=1:length(tmp) %loop over reference
if tmp(r)==comp_value %compare
tmp(r)=[]; %eclude
break
end
end
end
if isempty(tmp) % check whether all numbers are gone
result=n+1;
else
result=tmp(1);
end
output:
result =
2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.