Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Solve Cryptarithmetic Puzzle in Prolog

I have to write a Prolog program for solving a cryptarithmetic puzzle.

I need to write a function solve([A, M, P, D, Y]) which assigns the variables [A, M, P, D, Y] to values from 0 to 9 so that it satisfies the equation AM+PM=DAY. Each variable is assigned to a different value, and A, P, and D cannot be equal to 0.

I started writing this function, but ran into problems running my program. I set the restrictions of A, P, and D not being zero. As I was going through the algorithm, I realized that D has to be 1, so I defined that in the beginning of my program. I defined two different variables for M (M1 and M2) and set them equal to each other, since the different M’s in the puzzle should be assigned to the same value. I assigned locations to the different variables and added them up based on the puzzle. I accounted for any variables being carried with carry in variables. My program compiles but the function does not execute.

solve([A, M1, M2, P, D, Y]):- D is 1,
A/=0,
P/=0,
D/=0,
M1 = M2,
select(M1, [0,2,3,4,5,6,7,8,9], R1),
select(M2, R1, R2),
Y is (M1+M2) mod 10,
C1 is (M1+M2) // 10,
select(Y, R2, R3),
select(A, R3, R4),
select(P, R4, R5),
select(D, R5, R6),
A is (A+P+C1) mod 10,
D is (A+P+C1)// 10.

What am I doing wrong? Is there something wrong with my variable definitions? Do I need to define two different M variables, or is one sufficient?

like image 980
codergirl Avatar asked Dec 14 '12 00:12

codergirl


1 Answers

Here is my solution for your puzzle. We simply rely on PROLOG's backtracking. We select all variables first, then check the puzzle conditions. I don't think that you need to define two Ms.

solve([A,M,P,D,Y]):- 
select(A,[0,1,2,3,4,5,6,7,8,9],WA), % W means Without
not(A=0),
select(M,WA,WMA),
select(P,WMA,WMAP),
not(P=0),
select(D,WMAP,WMAPD),
not(D=0),
select(Y,WMAPD,WMAPDY),
DAY is 100*D+10*A+Y,
AM  is 10*A+M,
PM  is 10*P+M,
DAY is AM+PM.
like image 71
ssbarbee Avatar answered Sep 25 '22 00:09

ssbarbee