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. For example, if the input is [1, 2, 3], the output would be 4. If the input is [4, 0, 1, -10], output =2

This funtion worked for the vector [1,2,3,4] but not for [4, 1, 0, -10]
function [ ] = nextinteger(v)
n = max(v);
if n<0
n=0
else
n=n+1
end
end

댓글 수: 2

max([4, 1, 0, -10]) is 4, and you would transform that to 5. However, the question is not about one more than the largest value: it is about the first positive value that is not in the list. 1 is in the list, 2 is not, 3 is not, 4 is, 5 is not... smallest that is not in the list is 2.
so would my function here be correct?

댓글을 달려면 로그인하십시오.

답변 (2개)

Andrei Bobrov
Andrei Bobrov 2017년 10월 13일
편집: Andrei Bobrov 2017년 10월 13일
function out = nextinteger(v)
z = sort(v(v > 0));
s = setdiff(1:floor(z(end))+1,z);
out = s(1);
end
use
>> v = [6*rand(8,1) - 4;1;3];
>> v = v(randperm(10))
v =
-2.4935
0.88571
-2.4743
-1.9001
1.5756
1.0443
3
1
-2.5389
-2.8204
>> nextinteger(v)
ans =
2
>>
Stephen23
Stephen23 2017년 10월 14일
편집: Stephen23 2017년 10월 14일
Currently your code only calculates the value 1+max(v), whereas you need to identify the first integer that is not in v, something like this:
function out = nextinteger(v)
tmp = 1:1+max(v); % positive integers
tmp = tmp(~ismember(tmp,v)); % not in v
out = tmp(1); % the first one
end
and tested:
>> nextinteger([1,2,3])
ans = 4
>> nextinteger([4,1,0,-10])
ans = 2
>>

댓글 수: 2

is it possible to do this with only for, if and while loops?
You will also need some indexing, some assignments, and some comparison operations.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2017년 10월 13일

댓글:

2020년 8월 8일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by