Skip to content

Instantly share code, notes, and snippets.

@zebreus
Last active April 15, 2021 12:47
Show Gist options
  • Save zebreus/6aa120d545b3fcacb0ed1b15e5696b1e to your computer and use it in GitHub Desktop.
Save zebreus/6aa120d545b3fcacb0ed1b15e5696b1e to your computer and use it in GitHub Desktop.
A simple kakuro solver using clp in prolog
:- use_module(library(clpfd)).
% A simple test kakuro
kakuroValues1(Configuration, Values) :-
Configuration = [
[21,[A1,A2,A3]],
[11,[B1,B2,B3]],
[10,[C1,C2,C3]],
[23,[A1,B1,C1]],
[12,[A2,B2,C2]],
[ 7,[A3,B3,C3]]
],
Values = [A1,A2,A3,
B1,B2,B3,
C1,C2,C3].
% A normal kakuro
kakuroValues2(Configuration, Values) :-
Configuration = [
[12,[A1,A2]],
[17,[B1,B2,B3,B4]],
[17,[C1,C2]],
[ 4,[C3,C4]],
[24,[D1,D2,D3,D4]],
[ 9,[E1,E2]],
[16,[B1,C1]],
[28,[B2,C2,D1,E1]],
[ 4,[A1,B3]],
[ 7,[D2,E2]],
[22,[A2,B4,C3,D3]],
[ 6,[C4,D4]]
],
Values = [A1,A2,
B1,B2,B3,B4,
C1,C2,C3,C4,
D1,D2,D3,D4,
E1,E2].
% A more complex kakuro
kakuroValues3(Configuration, Values) :-
Configuration = [
[12,[A1,A2]],
[39,[A3,A4,A5,A6,A7,A8]],
[ 9,[B1,B2]],
[21,[B3,B4,B5,B6,B7,B8]],
[30,[C1,C2,C3,C4,C5,C6,C7]],
[25,[D1,D2,D3,D4,D5]],
[ 6,[D6,D7,D8]],
[17,[E1,E2]],
[26,[E3,E4,E5,E6,E7,E8]],
[ 3,[F1,F2]],
[15,[F3,F4]],
[25,[G1,G2,G3,G4,G5,G6]],
[ 7,[G7,G8]],
[ 8,[H1,H2,H3]],
[19,[H4,H5,H6,H7,H8]],
[41,[I1,I2,I3,I4,I5,I6,I7]],
[34,[J1,J2,J3,J4,J5,J6]],
[13,[J7,J8]],
[22,[K1,K2,K3,K4,K5,K6]],
[ 4,[K7,K8]],
[17,[A1,B1]],
[ 9,[D1,E1]],
[11,[G1,H1]],
[13,[J1,K1]],
[20,[A2,B2,C1,D2,E2]],
[21,[G2,H2,I1,J2,K2]],
[ 8,[C2,D3]],
[22,[F1,G3,H3,I2,J3,K3]],
[41,[A3,B3,C3,D4,E3,F2,G4]],
[ 6,[I3,J4,K4]],
[15,[A4,B4,C4,D5,E4]],
[17,[G5,H4,I4,J5,K5]],
[ 8,[A5,B5,C5]],
[42,[E5,F3,G6,H5,I5,J6,K6]],
[38,[A6,B6,C6,D6,E6,F4]],
[ 7,[H6,I6]],
[19,[A7,B7,C7,D7,E7]],
[22,[G7,H7,I7,J7,K7]],
[15,[A8,B8]],
[11,[D8,E8]],
[ 3,[G8,H8]],
[11,[J8,K8]]
],
Values = [A1,A2,A3,A4,A5,A6,A7,A8,
B1,B2,B3,B4,B5,B6,B7,B8,
C1,C2,C3,C4,C5,C6,C7,
D1,D2,D3,D4,D5,D6,D7,D8,
E1,E2,E3,E4,E5,E6,E7,E8,
F1,F2,F3,F4,
G1,G2,G3,G4,G5,G6,G7,G8,
H1,H2,H3,H4,H5,H6,H7,H8,
I1,I2,I3,I4,I5,I6,I7,
J1,J2,J3,J4,J5,J6,J7,J8,
K1,K2,K3,K4,K5,K6,K7,K8].
% Add constraint
kakuro([]).
kakuro([[Target, Numbers]| Rest]) :-
Numbers ins 1..9,
all_distinct(Numbers),
sum(Numbers, #=, Target),
kakuro(Rest).
/*
Example for solving the kakuro specified in kakuroValues3
:- kakuroValues3(A,X), kakuro(A), label(X).
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment