Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get one of many possible solutions in Prolog

I'm trying to learn Prolog. I looked at this script:

:- use_module(library(clpfd)).
puzzle([S,E,N,D] + [M,O,R,E] = [M,O,N,E,Y]) :-
   Vars = [S,E,N,D,M,O,R,Y],
   Vars ins 0..9,
   all_different(Vars),
   S*1000 + E*100 + N*10 + D + M*1000 + O*100 + R*10 + E #= M*10000 + O*1000 + N*100 + E*10 + Y,
   M #\= 0,
   S #\= 0.

Source: https://github.com/Anniepoo/prolog-examples/blob/master/sendmoremoney.pl

I run it like so and get some output:

$ swipl -q -s sendmoremoney.pl
?- puzzle(X).
X = ([9, _G2009, _G2012, _G2015]+[1, 0, _G2024, _G2009]=[1, 0, _G2012, _G2009, _G2042]),
_G2009 in 4..7,
all_different([9, _G2009, _G2012, _G2015, 1, 0, _G2024, _G2042]),
91*_G2009+_G2015+10*_G2024#=90*_G2012+_G2042,
_G2012 in 5..8,
_G2015 in 2..8,
_G2024 in 2..8,
_G2042 in 2..8.

It looks like that is giving me a range of possible values for each letter. But how can I get a single solution where each letter is assigned to one of the possible values? Seems like a very basic question, but I can't figure it out.

like image 888
Jesse Aldridge Avatar asked Oct 18 '22 04:10

Jesse Aldridge


1 Answers

Ok, looks like this wasn't so much a Prolog question as a clpfd question.

?- puzzle(As + Bs = Cs), label(As).
As = [9, 5, 6, 7],
Bs = [1, 0, 8, 5],
Cs = [1, 0, 6, 5, 2] ;
false.

Found my answer here: http://www.swi-prolog.org/man/clpfd.html

like image 134
Jesse Aldridge Avatar answered Oct 21 '22 04:10

Jesse Aldridge