Write a function that accepts string as a parameter, returning evaluated value of expression in dice notation, including addition and multiplication.
To
233 characters
This solution should be fully generic, in that it can handle just about any string you throw at it, even something crazy such as:
43d29d16d21*9 + d7d9*91 + 2*d24*7
Need to define this globally:
let r = new System.Random()
Fully obfuscated version:
let f(s:string)=let g d o i p (t:string)=t.Split([|d|])|>Array.fold(fun s x->o s (p x))i in g '+'(+)0(g '*' (*) 1 (fun s->let b=ref true in g 'd'(+)1(fun t->if !b then b:=false;(if t.Trim()=""then 1 else int t)else r.Next(int t))s))s
Readable version:
let f (s:string) =
let g d o i p (t:string) =
t.Split([|d|]) |> Array.fold (fun s x -> o s (p x)) i
g '+' (+) 0 (g '*' (*) 1 (fun s ->
let b = ref true
g 'd' (+) 1 (fun t ->
if !b then b := false; (if t.Trim() = "" then 1 else int t)
else r.Next(int t)) s)) s
I'm challenging someone to beat this solution (in any language) without using eval
or regular expressions. I think it's likely to be possible, but I am interested in seeing the approach still.