1

I trying to create compact code in prolog that sovles systems of equations.

For example, in this case, the assumptions must be

A+B-C-D=4, A+B+C+D=14, A-B+C-D=2.

I'm trying to have it where it solves all combinations possible for A, B, C, and D but satisfies all 3 equations. They can only be #'s 0-9 though but somehow show all possible solutions/combinations.

So after running the query, it would output something like

Crypto(A,B,C,D)

A = 8, B = 1, C = 0, D = 5.

^That would be one solution. But I need to show all possible.

I'm kind of lost as to how to satisfy all 3 in Prolog. Thank you.

false
  • 10,264
  • 13
  • 101
  • 209
dracogale
  • 13
  • 3

1 Answers1

0

You can solve it by taking out one element from the domain of the variables and assign it to them such that every variable has a different number assigned to it. It's a brute force method.

takeout(X, [X|R], R).
takeout(X, [Y|Xs], [Y|Ys]):- takeout(X, Xs, Ys).

aas(X,L,L1):- takeout(X,L,L1).

crypto(A,B,C,D):-
        L=[0,1,2,3,4,5,6,7,8,9],
        aas(A,L,L1),aas(B,L1,L2),aas(C,L2,L3),aas(D,L3,_),
        A+B-C-D=:=4,
        A+B+C+D=:=14,
        A-B+C-D=:=2,
        nl.

aas(X,L,L1). used for assigning values to the variables. takeout function is used for taking out one element and return a list excluding the element taken out.

OUTPUT

?- crypto(A,B,C,D).
A = 3,
B = 6,
C = 5,
D = 0

A = 5,
B = 4,
C = 3,
D = 2

A = 7,
B = 2,
C = 1,
D = 4

A = 8,
B = 1,
C = 0,
D = 5

This program prints all the possible solutions to that equation A+B-C-D=4, A+B+C+D=14, A-B+C-D=2. Hope this answers your question.

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
  • Why do you insist that the variables are different? – false Dec 08 '19 at 15:00
  • It's a cryptarthematic sum. where variables domain range is (0,9) and each variable should have a different value. Those are basic constraints that need to be satisfied. – Ch3steR Dec 08 '19 at 16:47
  • You can do one thing if variables can be the same then rewrite the `crypto` query as follows `crypto(A,B,C,D):- L=[0,1,2,3,4,5,6,7,8,9], aas(A,L,_),aas(B,L,_),aas(C,L,_),aas(D,L,_), A+B-C-D=:=4, A+B+C+D=:=14, A-B+C-D=:=2, nl.` You will get all possible solutions for the equation. – Ch3steR Dec 08 '19 at 16:53