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 ExchangeLoops 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