sutrivmz
sutrivmz

Reputation: 11

Arithmetic operations in prolog

How is it possible to obtain 28 using 7 10 3 2 in this order and without using parentheses?I've been thinking for the past 1 1/2 hours and I couldn't get anywhere.

Upvotes: 1

Views: 245

Answers (2)

repeat
repeat

Reputation: 18726

This answer builds on the previous one by @WillNess, trying to make it simpler:

x_y_xy(A, B, A + B).
x_y_xy(A, B, A - B).
x_y_xy(A, B, A * B).
x_y_xy(A, B, A div B).

puzzle(C) :- 
   x_y_xy(7, 10, A),
   x_y_xy(A, 3,  B),
   x_y_xy(B, 2,  C).

Sample use:

?- puzzle(Expr), Expr =:= 28.
Expr = (7+10-3)*2 ;
false.

Upvotes: 2

Will Ness
Will Ness

Reputation: 71119

Just do it step by step, passing the changing state along.

step(S,A,X, S2,A2) :-
   (  S = [+ | S2], A2 is A + X
   ;  S = [- | S2], A2 is A - X
   ;  S = [* | S2], A2 is A * X
   ;  S = [/ | S2], A2 is A div X 
   ).

puzzle(S) :- 
   step(S,  7, 10,  S2, A2),
   step(S2, A2, 3,  S3, A3),
   step(S3, A3, 2,  [], 28).

Trying:

?- puzzle(X).
X = [+,-,*] ;
false.

Upvotes: 2

Related Questions