如何解决 Prolog 中的密码谜题 [英] How to Solve Cryptarithmetic Puzzle in Prolog

查看:53
本文介绍了如何解决 Prolog 中的密码谜题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须编写一个 Prolog 程序来解决一个密码谜题.

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

我需要编写一个函数solve([A, M, P, D, Y]) 将变量[A, M, P, D, Y] 分配给0 到9 之间的值,使其满足方程上午+下午=天.每个变量被赋予不同的值,A、P、D不能等于0.

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.

我开始编写这个函数,但在运行我的程序时遇到了问题.我将 A、P 和 D 的限制设置为不为零.当我在研究算法时,我意识到 D 必须是 1,所以我在程序的开头定义了它.我为 M 定义了两个不同的变量(M1 和 M2),并将它们设置为彼此相等,因为拼图中不同的 M 应该分配给相同的值.我为不同的变量分配了位置,并根据谜题将它们相加.我考虑了携带进位变量的任何变量.我的程序可以编译,但函数没有执行.

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.

我做错了什么?我的变量定义有问题吗?我需要定义两个不同的 M 变量,还是一个就足够了?

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?

推荐答案

这是我为您的难题提供的解决方案.我们只是依靠 PROLOG 的回溯.我们首先选择所有变量,然后检查拼图条件.我不认为你需要定义两个女士.

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.

这篇关于如何解决 Prolog 中的密码谜题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆