2017-07-01 98 views
3

我有100萬行長期詞典:查找單詞的所有可能的組合在給定的格式

w([w,o,r,d]). 
w([h,a,p,p,y]). 
w([q,u,e,s,t,i,o,n]). 
... 

現在我在腳本的工作,將返回所有可能的話,把滿足給定的格式。

例如:

w([A,B,C]), w([B,C]), A \== B, A \== C, B \== C. 

我發現,使不同的所有變量的源:

alldif([]). 
alldif([E|Es]) :- 
    maplist(dif(E), Es), 
    alldif(Es). 

所以,現在我打電話:

w([A,B,C]), w([B,C]), alldif([A,B,C]). 

現在我想的是,變量A是[a,e,i,o,t,l]中的一個。使用帶有約束編程

member(A, [a,e,i,o,t,l]). 

但它是速度快:我能做到這一點使用(?):

A in [a,e,i,o,t,l] 

all_different([A,B,C]). 

我有種馬上套牢。這個想法是在.txt文件中逐行生成所有可能的選項。

我設法串聯詞到語句中使用:

g([A,B,C], W1), g([B,C], W2), alldif([A,B,C]), buildStat([W1,W2], Statement). 

其中:

g(Format, Word):- 
    list_to_set(Format, Uniques), 
    alldif(Uniques), 
    w(Format), 
    atomic_list_concat(Format, '', Atom), atom_string(Atom, Word). 

insertSpaces([A], [A]). 
insertSpaces([Word | Rest], OutWords):- 
    insertSpaces(Rest, OutWordsRest), 
    OutWords = [Word, " " | OutWordsRest]. 


buildStat(Words, Statement):- 
    insertSpaces(Words, OutWords), 
    with_output_to(atom(Statement), maplist(write, OutWords)). 

但我不知道怎麼用線來保存所有possibible語句插入文件行。 幫助,將不勝感激。

回答

2

排出所有解決方案的一個簡單的技巧是強制回溯通過false/0

例如,假設你有一個收益率回溯所有解決方案的斷言:

 
?- solution(S). 

您可以發出所有的解決方案是這樣的:

 
?- solution(S), 
    print_solution(S), 
    false. 

,你必須定義print_solution/1,因爲你想產生你想要的格式。

例如,您可以將此類解決方案打印到標準輸出,然後將管道輸出到文件中。具體情況取決於您的Prolog  系統,可能如下所示:

 
$ prolog --goal 'ignore((solution(S),portray_clause(S),false)),halt' >output.txt 
+0

「假」解決了生成所有問題。 你能以更快的速度幫助我嗎(要求所有變量不同,例如指定A必須是[a,e,i,o],或者先找到字典中的單詞?) –

+1

請爲此另外提出一個問題。另外,嘗試使用'time/1'來測量所花費的時間,比如'? - time(your_goal).'。這將幫助您找出哪種方法更快。 – mat