Re: Arithmetic puzzle



bart demoen schreef:
On Sun, 03 Dec 2006 05:07:06 -0800, ronaldo wrote:

Hello guys,

I am quite novice in prolog and I have been trying to do it by
myself while following this thread. This is the solution I have
elaborated:
...
Could you please give me constructive comments?
Many Thanks in advance :)

Maybe we can first agree on what to expect - the query

?- find([1,2,3],4).

fails for your program, while my program prints as answers
4 = 2 - 1 + 3
Yes ;
4 = 2 + 3 - 1
Yes ;
4 = 3 - 1 + 2
Yes ;
4 = 3 + 2 - 1
Yes ;
No more !

Your generate uses the numbers only in the order of the inputlist.
Did you intend the failure ?


Cheers

Bart Demoen

I wrote a small program myself (cf attachment). I have been playing with a bit, so the version attached is a tiny bit more general then the original problem, and will find somewhat more solutions. But it is easy enough to play with different settings: you can disallow the extra operators, disallow permutations, disallow the adding of sign operators, etc. by some simple changes to the program.

Cheers,
Peter

find(Nums, Outcome, Expression) :-
permutation(Nums, Perm),
generate(Perm, Expression),
Outcome is Expression.

generate(Ns, Expr) :- generate_(Ns, Expr).
generate(Ns, -Expr) :- generate_(Ns, Expr).

generate_([N], N).
generate_([N|Ns], Expr) :-
operator(Op),
generate(Ns, ExprX),
( Expr =.. [Op,N,ExprX] ; Expr =.. [Op,ExprX,N] ).
generate_([Na,Nb|Ns], Expr) :-
N is Na * 10 + Nb,
generate([N|Ns], Expr).


operator(+).
operator(-).
operator(*).
operator(/).