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

조회 수: 1 (최근 30일)
Oscar Tsang
Oscar Tsang 2019년 3월 3일
댓글: Oscar Tsang 2019년 3월 3일
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