Created
June 29, 2013 20:59
-
-
Save eldesh/5892647 to your computer and use it in GitHub Desktop.
https://gist.github.com/yonta/5851577#file-sendmoremoney2-sml に触発されて書いてみた。力ずくで解く例。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(** | |
* SEND | |
* + MORE | |
* ------ | |
* MONEY | |
* | |
* S,E,N,D,M,O,R,Y | |
* | |
* run: | |
* - Option.app (print o pp) (search ()) | |
*) | |
structure L = List | |
fun toInt xs = L.foldl (fn (x,i)=> x + i * 10) 0 xs | |
fun pp (xs as [S,E,N,D,M,O,R,Y]) = | |
let | |
val int = Int.toString | |
in | |
concat[" ", concat(map int [S,E,N,D]), "\n" | |
,"+ ", concat(map int [M,O,R,E]), "\n" | |
,"------\n" | |
," " , concat(map int [M,O,N,E,Y]), "\n" | |
] | |
end | |
| pp _ = raise Domain | |
fun unique [] = true | |
| unique (x::xs) = not (L.exists (fn e=>e=x) xs) | |
andalso unique xs | |
fun isSolved (xs as [S,E,N,D,M,O,R,Y]) = | |
let | |
val send = toInt [S,E,N,D] | |
val more = toInt [M,O,R,E] | |
val money = toInt [M,O,N,E,Y] | |
in | |
unique xs | |
andalso 0<>S | |
andalso 0<>M | |
andalso send + more = money | |
end | |
| isSolved _ = false | |
fun toList x = | |
let | |
fun toList' v = if v < 10 then [v] | |
else (v mod 10)::toList' (v div 10) | |
in rev (toList' x) | |
end | |
fun extend n xs = | |
let | |
val len = length xs | |
in | |
if len < n | |
then L.tabulate (n - len, fn _=> 0)@xs | |
else xs | |
end | |
fun permutation xs = | |
let | |
fun next xs = toList ((toInt xs) + 1) | |
fun go xs = if unique xs then xs | |
else go (next xs) | |
in go (next xs) | |
end | |
fun search () = | |
let | |
fun search' xs = | |
if isSolved xs | |
then SOME xs | |
else search' (permutation xs) | |
in | |
search' [0] | |
end ; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment