Evaluate dice rolling notation strings

前端 未结 14 1428
甜味超标
甜味超标 2021-01-30 14:55

Rules

Write a function that accepts string as a parameter, returning evaluated value of expression in dice notation, including addition and multiplication.

To

14条回答
  •  说谎
    说谎 (楼主)
    2021-01-30 15:21

    F# (no eval and no regex)

    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.

提交回复
热议问题