finding the lowest common ancestor between 2 cells array

조회 수: 1 (최근 30일)
Jwana
Jwana 2012년 11월 8일
Hi, I have a code that can find the lowest common ancestor ( lowest common character) and the common chaarcters for 2 vectors, the code is:
cc= ['a0.c2.b2.d6'] ;
pc= ['a0.c1.c3.d5'];
for i=1:min(length(pc),length(cc))
if cc(i)==pc(i)
q(i)=cc(i);
else
break
end
end
if strcmp(q,pc) | strcmp(q,cc)
LCA=q;
else
disp('There is no LCA')
end
The problem of this code is that it takes the common character even if they are not has the same supnumber, like for eaxmple, the previous cc and pc , the answer will be :
There is no LCA
q =
a0.c
note that it takes c as common between c2 and c1 which is not accepted. also it takes the 'dot' between character such as :
cc= ['a0.c4.b2.d6'] ;
pc= ['a0.c4.c3.d5'];
for i=1:min(length(pc),length(cc))
if cc(i)==pc(i)
q(i)=cc(i);
else
break
end
end
if strcmp(q,pc) | strcmp(q,cc)
LCA=q;
else
disp('There is no LCA')
end
q
the answer will be:
There is no LCA
q =
a0.c4.
advice me please

채택된 답변

Andrei Bobrov
Andrei Bobrov 2012년 11월 8일
편집: Andrei Bobrov 2012년 11월 8일
p1 = regexp(pc,'\.','split');
c1 = regexp(cc,'\.','split');
ii = ismember(p1,c1);
k = p1(1:find(ii == 0,1,'first')-1);
t = reshape([k;repmat({'.'},1,numel(k))],1,[]);
q = char(strcat(t{1:end-1}));
or
i1 = [0 strfind(pc,'.') numel(pc)+1];
i2 = [0 strfind(cc,'.') numel(cc)+1];
q = [];
for jj = 1:numel(i1)-1
k = pc(i1(jj)+1:i1(jj+1)-1);
if strcmp(k,cc(i2(jj)+1:i2(jj+1)-1))
q = [q k '.'];
else
break
end
end
q = q(1:end-1);

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Particle & Nuclear Physics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by