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

1 view (last 30 days)
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

Answers (1)

Image Analyst
Image Analyst on 3 Mar 2019
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 Comments
Oscar Tsang
Oscar Tsang on 3 Mar 2019
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

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!