フィルターのクリア

Why is my code messing up on this specific test case?

1 回表示 (過去 30 日間)
Shahriyar Karim
Shahriyar Karim 2020 年 3 月 13 日
コメント済み: Shahriyar Karim 2020 年 3 月 14 日
function [E] = lostAtSeaCucumber(vec,name)
n = [];
[r,c] = size(vec)
for i = 1:c
n = [n,vec(i).Next];
end
r(1) = n(1);
for i = 2:length(n)
r(end+1) = n(r(i-1));
end
s = [1 r(1:length(n)-1)];
final = [];
for i = 1:length(s)
if ismember(vec(s(i)).Name,name)
final = [final, vec(s(i)).Name,' '];
break
end
final = [final, vec(s(i)).Name,' ']
end
[E] = final
end
My code is messing up on this test case:
1x5 struct: (numbers are respective to the name above)
'Max' 'Cheyenne' 'Priyana' 'Beau' 'Gordon'
5 1 5 2 3
EDIT: the correct output should be 'Max Gordon Priyana Gordon' but I'm getting 'Max Gordon Priyana Gordon Priyana'

採用された回答

BobH
BobH 2020 年 3 月 13 日
function out = lostAtSeaCucumber( vec, srch )
collected = ''; % temporary storage for names
visited = zeros(size(vec));
i = 1;
while( true )
% Always add the name
collected{end+1} = vec(i).Name;
% If we've added this name a second time, we're all done
% If the name added matches the search name, we're all done
if( visited(i) == 1 || strcmp(vec(i).Name, srch ) )
break;
else
visited(i) = 1;
i = vec(i).Next;
end
end
% run all the collected names into a single string with a space between
out = sprintf( '%s ', collected{:} );
out(end) = []; % chop the last space off
end
  1 件のコメント
Shahriyar Karim
Shahriyar Karim 2020 年 3 月 14 日
This works; just had to remove the
out(end) = []
because the question wanted the final blankspace included in the output.
Thank you again!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeDatabase Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by