What is wrong with the code?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
GEORGIOS BEKAS
am 23 Jan. 2018
Kommentiert: GEORGIOS BEKAS
am 24 Jan. 2018
I am trying to find the logest subsequence of 1s in a string. I am doing something wrong.
s='0101010111000101110001011100010100001110110100000000110001001000001110001000111010101001101100001111'
c=[]
counter = 0
for i = 2:length(s)
while str2num(s(i)) == 1 && str2num(s(i)) == str2num(s(i-1))
counter = counter+1
c = [c,counter]
if str2num(s(i)) ==0
counter = 0
end
end
end
2 Kommentare
Walter Roberson
am 23 Jan. 2018
hint: instead of doing str2num() and comparing to 1, you can just compare s(i) == '1', and you can compare s(i) == s(i-1)
Akzeptierte Antwort
Birdman
am 24 Jan. 2018
Use regexp.
regexp(s,'1*','match')
and you will find that the longest subsequence consists of 4 elements.
Weitere Antworten (1)
Walter Roberson
am 24 Jan. 2018
You have
counter = 0;
for i = 2:length(s)
while str2num(s(i)) == 1 && str2num(s(i)) == str2num(s(i-1))
counter = counter+1
c = [c,counter]
if str2num(s(i)) ==0
counter = 0
end
end
Trace it through.
Start with i = 2.
s(2) == 1 but s(1) is not 1, so end the while.
Go on to i = 3. s(3) == 0, so end the while.
Go on to i = 4. s(4) == 1, but s(3) is not 1, so end the while.
Go on to i = 5.... etc. You keep ending the while immediately until...
i = 9. s(9) == 1 and s(9) and s(8) are both 1, so enter the while loop.
Inside the while loop, increment counter to 1 and adjust c. s(9) is still not 0 so do not reset counter to 0. Continue around in the while loop.
i is still 9. s(9) and s(8) are still both 1, so enter the while loop. Inside the while loop, increment counter to 2 and adjust c. s(9) is still not 0, so do not reset counter to 0. Continue in the while loop.
i is still 9. s(9) and s(8) are still both 1, so enter the while loop. Inside the while loop, increment counter to 3 and adjust c. s(9) is still not 0, so do not reset counter to 0. Continue in the while loop.
...
ummm... when do we end the while loop? The while loop tests s(i) and s(i-1) but does not change either location and does not change i, so once entered, the while loop will never end.
2 Kommentare
Siehe auch
Kategorien
Mehr zu Whos finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!