Skip to content

Instantly share code, notes, and snippets.

@pyrocat101
Created March 10, 2014 22:35
Show Gist options
  • Save pyrocat101/9475931 to your computer and use it in GitHub Desktop.
Save pyrocat101/9475931 to your computer and use it in GitHub Desktop.
Generalized Verbal Arithmetic in Prolog.
pad(W1, W2, X, Y) :-
length(W1, L1),
length(W2, L2),
padZero(W1, W2, L1, L2, X, Y).
padZero(W1, W2, L, L, [0|W1], [0|W2]).
padZero(W1, W2, L1, L2, X, Y) :- L1 #> L2, pad(W1, [0|W2], X, Y).
padZero(W1, W2, L1, L2, X, Y) :- L1 #< L2, padZero(W2, W1, L2, L1, Y, X).
stripZero([], []).
stripZero([0|T], T).
stripZero([H|T], [H|T]) :- H #> 0.
sum([], [], [], 0, 0).
sum([H1|T1], [H2|T2], [H3|T3], C1, C2) :-
sum(T1, T2, T3, C2, _),
H3 #= (H1 + H2 + C2) rem 10,
C1 #= (H1 + H2 + C2) // 10.
verbalArithmetic([], [], [], []).
verbalArithmetic(V, [H1|W1], [H2|W2], [H3|W3]) :-
fd_domain(V, 0, 9),
fd_all_different(V),
H1 #\= 0, H2 #\= 0, H3 #\= 0,
pad([H1|W1], [H2|W2], X, Y),
sum(X, Y, Z, _, _),
stripZero(Z, [H3|W3]),
fd_labeling(V).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment