Prolog - Can you solve this 2nd grade problem that has baffled adults?
The problem:
The solution:
:- use_module(library(clpfd)).
:- use_module(library(lists)).
all_values([6,6,2,2,8,8, 0, 0, 0]).
val(X) :- all_values(AV), member(X, AV).
solve(T1,T2,T3,Result) :-
all_values(ALLVALUES),
POSSIBLE_VALS= [X1, X2, X3, X4, X5, X6, X7, X8, X9],
permutation(ALLVALUES, POSSIBLE_VALS),
T1 #= X1,
T1 #< 10,
T2 #= 10*X2 + X3,
T2 #< 100, T2 #>= 10,
T3 #= 100*X4 + 10*X5 + X6,
T3 #< 1000, T3 #>=100,
Result #= 100*X7 + 10*X8 + X9,
Result #= T1+T2+T3.
And to query:
solve(T1, T2, T3, Result),
format(' ~w~n ~w~n+ ~w~n-----~n ~w~n', [T1,T2,T3,Result]).
Giving lots of results!
6
20
+ 800
-----
826
Also, swish is great
UPDATE from reddit thread. Suggestion is to use global_cardinality. I think this uses clpfd better. The solution above might not even have needed clpfd as it enumerated all possibilities anyways.
In below block, could uncomment the % depending on if you think you may have leading 0’s. I think leading 0’s are not allowed. It would be untrue to say ‘2-digit addend’ but the number be ‘06’. But possibly ‘1-digit addend’ of 0 would be legit. Need some math lawyers here 😁
solve2(T1, T2, T3, Result) :-
Vs = [V1, V2, V3, V4, V5, V6, V7, V8, V9],
global_cardinality(Vs, [0-3,2-2,6-2,8-2]),
T1 #= V1,
%T1 #> 0,
T2 #= 10*V2 + V3,
%T2 #< 100, T2 #>= 10,
T3 #= 100*V4 + 10*V5 + V6,
%T3 #< 1000, T3 #>=100,
Result #= 100*V7 + 10*V8 + V9,
T1 + T2 + T3 #= Result,
label([T1, T2, T3, Result]).