length of the largest sub sequence sorted in a non-decreasing order.

1 次查看(过去 30 天)
For an assignment, I have done question 3a, but i don't know how would do/ approach question 3b. Any help would be appriciated. :)
The questions was:
Generate a sequence of 1000 random integers between 1 and 100.
(a) Using a loop, count the number of times three consecutive numbers are sorted in a non-descending order. Display the count in the command window.
(b)* Using nested loops, find the length of the largest subsequence sorted in a non-decreasing order. Display the result in the command window.
I have provided the code i have done for question 3a
h=randi(100,1,1000)
count =0
for i =1:998
if h(i)<=h(i+1) && h(i+1) <= h(i+2)
count = count+1
end
end

回答(1 个)

Image Analyst
Image Analyst 2019-3-3
Inside the "if", you know you have a sequence of at least 3 in a row. If there are 20 numbers in that sequence, you're going to have more than 1 count for that sequence. Not sure what is wanted. For example, is [3,4,5,6] one sequence or two? If it's one, then you might have to switch to a while loop.
Anyway, inside the "if" you need to have a while, something like
k2 = i;
if h2 < length(h);
while h(k2+1) > h(k2)
% etc incrementing the length of this particular sequence.
  4 个评论
Oscar Tsang
Oscar Tsang 2019-3-3
is this it, becasue its a endless loop.
h=randi(100,1,1000)
count=0;
for i =1:998
if h(i)<=h(i+1) && h(i+1) <= h(i+2)
while h(k2+1) > h(k2)
count = count+1
end
end
end

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by