Skip to content

Instantly share code, notes, and snippets.

@Heimdell
Last active August 29, 2015 14:26
Show Gist options
  • Save Heimdell/12c2d3fcaaa059c07969 to your computer and use it in GitHub Desktop.
Save Heimdell/12c2d3fcaaa059c07969 to your computer and use it in GitHub Desktop.
SEND + MORE = MONEY
import Data.List (permutations)
import Control.Monad (guard)
main = putStrLn $ head solutions
solutions = do
let range = [0.. 9]
[s,e,n,d,m,o,r,y,_,_] <- permutations range
let a = fromDigits [s,e,n,d]
b = fromDigits [m,o,r,e]
c = fromDigits [m,o,n,e,y]
guard $ m == 1
guard $ a + b == c
return $ unwords [show a, "+", show b, "=", show c]
fromDigits = foldl (\a b -> a * 10 + b) 0
:- use_module(library(lists)).
solve(A + B = C) :-
permutation([0,2,3,4,5,6,7,8,9], [S,E,N,D,O,R,Y | _]),
M = 1,
S \= 0,
fromDigits( [S,E,N,D], A),
fromDigits( [M,O,R,E], B),
fromDigits([M,O,N,E,Y], C),
C is A + B.
fromDigits(List, Result) :-
foldl(attach, List, 0, Result).
attach(A, B, C) :- C is B * 10 + A.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment