Created
May 11, 2015 16:54
-
-
Save bjartwolf/46474f8a468f6863b99f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
type symbol = Plus of int * symbol | Minus of int * symbol | Join of int * symbol |End | |
let merge (i1: int) (i2:int) = (int)(sprintf "%d%d" i1 i2) | |
let rec flatten (n: int) (s: symbol) = | |
match s with | |
| Join (a,t) -> flatten (merge n a) t | |
| _ -> (n,s) | |
let rest (symbol:symbol) = | |
match symbol with | |
| Plus (u,v) -> (u,v) | |
| Minus (u,v) -> (-u,v) | |
| End -> (0, End) | |
| _ -> raise (System.Exception "shoud not happen after flatten") | |
let rec calc (n: int) (s: symbol) : int = | |
let (x,t) = flatten n s | |
match t with | |
| End -> x | |
| Plus (a,b) -> x+ calc a b | |
| Minus (a,b) -> let (foo,bar) = flatten a b | |
let (baz,boo) = rest bar | |
x - foo + calc baz boo | |
| Join _ -> raise (System.Exception "shoud not happen after flatten") | |
let rec genSolutions (s:int) (stopp: int) = seq { | |
if s = stopp then yield (s, End) | |
else for i in genSolutions (s+1) stopp do | |
yield (s, Plus i) | |
yield (s, Minus i) | |
yield (s, Join i) | |
} | |
let rec prettyPrint (i: int, s:symbol) :string = | |
match s with | |
| End -> sprintf "%d" i | |
| Join (n,t) -> sprintf "%d" i + prettyPrint (n,t) | |
| Plus (n,t) -> sprintf "%d" i + "+" + prettyPrint (n,t) | |
| Minus (n,t) -> sprintf "%d" i + "-" + prettyPrint (n,t) | |
genSolutions 1 9 |> Seq.filter (fun (x,y) -> 100 = calc x y) |> | |
Seq.map((prettyPrint)) |> Seq.distinct |> Seq.toList |> printfn "%A" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment