2016-10-23 2 views
5

단어는 공백이나 문자열의 시작/끝 지점으로 구분 된 기호 문자입니다. 예를 들어. [w,o,r,d,1,' ',w,o,r,d,2].프롤로그에서 문자열의 모든 k-length 단어를 찾습니다.

주어진 문자열의 모든 k-length 단어를 찾아서 결과 문자열에 추가해야합니다 (공백으로 구분). 이 내가 K = 5의 경우, 예를 들어 기대하고있는 무슨이다 : 다른 사람이 간단한 해결책을 제시 할 수있는 희망

?- kthWords([w,o,r,d,1,'',w,r,d,'',w,o,r,d,2], 5, X). 
X = [w,o,r,d,1,'',w,o,r,d,2]. 

답변

3

에게 당신을 작동하는 것 같다 작성할 수

final_kthWords(L,K,Outlist):- 
     kthWords(L,K,L1), 
     reverse(L1,[_|T]), 
     reverse(T,Outlist). 

kthWords([],_,[]):-!. 
kthWords(L,K,L1):- 
    find_word(L,Word,L2), 
    length(Word,N), 
    (N=:=K-> append(Word,[' '|T],L1),kthWords(L2,K,T); 
    kthWords(L2,K,L1)). 

find_word([],[],[]). 
find_word([H|T],[H|T1],L):-dif(H,' '),find_word(T,T1,L). 
find_word([H|T],[],T):- H = ' '. 

kthWords/3 통화 단어를 찾아 find_word/2 마지막 kthWords 출력을 반환하는 경우 목록에 추가되지만 끝에는 ' '이 추가됩니다. final_kthWords(L,K,Outlist)/3 목록의 마지막에 추가 ' '을 제거하고 수행하고 오른쪽 목록을 반환하는 유일한 것은 : 반대없이

?- final_kthWords([w,o,r,d,1,' ',w,r,d,' ',w,o,r,d,2], 5, X). 
X = [w, o, r, d, 1, ' ', w, o, r, d, 2] ; 
false. 
+0

이것은 나에게 꽤 좋은 것 같습니다. thx :) –

+0

도움이 된 것을 기쁘게 생각합니다 !!! – coder

1

... 다음은

kthWordsH([], 0, _, R0, R0). 

kthWordsH([], N, _, _, []) :- 
    N \= 0. 

kthWordsH([' ' | Tl], 0, Len, W, Revult) :- 
    kthWordsH(Tl, Len, Len, [], Res0), 
    append(Res0, [' ' | W], Revult). 

kthWordsH([' ' | Tl], N, Len, _, Revult) :- 
    N \= 0, 
    kthWordsH(Tl, Len, Len, [], Revult). 

kthWordsH([H | Tl], 0, Len, _, Revult) :- 
    H \= ' ', 
    kthWordsH(Tl, Len, Len, [], Revult). 

kthWordsH([H | Tl], N, Len, Tw, Revult) :- 
    H \= ' ', 
    N \= 0, 
    Nm1 is N-1, 
    kthWordsH(Tl, Nm1, Len, [H | Tw], Revult). 

kthWords(List, Len, Result) :- 
    kthWordsH(List, Len, Len, [], Revult), 
    reverse(Revult, Result). 
+0

음, 흥미로운 해결책 :) +1 –

0

솔루션.

% return a word of k length, or return [] otherwise 
kword(K,L,W):- 
    length(L,K) -> append(L,[' '],W); W=[]. 

% if no more chars, then check final word in L and 
% append to word list Ls to return Lw 
kwords(K,[],L,Ls,Lw):- 
    kword(K,L,W), 
    append(Ls,W,Lw). 

% if char is space, then append to Ls if word of length K 
% if not space, append char to "in progress" work list L 
kwords(K,[C|Cs],L,Ls,Lw):- 
    ( C=' ' -> 
     ( kword(K,L,W), 
      append(Ls,W,Ls0), 
      L2 = [] 
     ); 
     ( append(L,[C],L2), 
      Ls0 = Ls 
     ) 
    ), 
    kwords(K,Cs,L2,Ls0,Lw). 

% intialise predicate call with empty word and empty result 
kthWords(Cs,K,L):- kwords(K,Cs,[],[],L). 
관련 문제