Find all possible combinations of words in a given format

I have a dictionary 100,000 lines long:

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

      

I am now working on a script that will return all possible words that match a given format.

For example:

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

      

I found a source that makes all the variables different:

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

      

So now I am calling:

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

      

Now I want the variable A to be one of [a, e, i, o, t, l]. I can do this using:

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

      

But it is faster (?) Using constraint programming with:

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

      

and

all_different([A,B,C]).

      

I'm stuck now. The idea was to generate all possible parameters in the .txt file line by line.

I was able to concatenate words into an operator using:

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

      

Where:

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)).

      

But I don't know how to save all possible entries to a file line by line. Help would be appreciated.

+3


source to share


1 answer


One simple trick to emit all solutions is forcing backtracking through false/0

.

For example, suppose you have a predicate that gives all backtracking solutions:

? - solution (S).

you can emit all solutions like this:



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

where you should define print_solution/1

as you want the format you want.

For example, you can print solutions like this to standard output and then pipe the output to a file. The specifics of this depend on your Prolog system and might look like this:

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


source







All Articles