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
Show older comments
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 Comments
Walter Roberson
on 13 Oct 2017
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.
Kristina Swais
on 13 Oct 2017
Answers (2)
Andrei Bobrov
on 13 Oct 2017
Edited: Andrei Bobrov
on 13 Oct 2017
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
>>
1 Comment
Seth Spatacean
on 8 Aug 2020
could you solve this using a while loop?
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 Comments
Hussein Moussaoui
on 15 Apr 2018
is it possible to do this with only for, if and while loops?
Walter Roberson
on 15 Apr 2018
You will also need some indexing, some assignments, and some comparison operations.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!