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 Kommentare

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?

Melden Sie sich an, um zu kommentieren.

Antworten (2)

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 am 14 Okt. 2017
Bearbeitet: Stephen23 am 14 Okt. 2017
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 Kommentare

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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 13 Okt. 2017

Kommentiert:

am 8 Aug. 2020

Community Treasure Hunt

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

Start Hunting!

Translated by