Evaluate dice rolling notation strings

前端 未结 14 1452
甜味超标
甜味超标 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:27

    Ruby, 87 characters, uses eval

    Here's my Ruby solution, partially based on the OP's. It's five characters shorter and only uses eval once.

    def f s
    eval s.gsub(/(\d+)?[dD](\d+)/){n=$1?$1.to_i: 1;n.times{n+=rand $2.to_i};n}
    end
    

    A readable version of the code:

    def f s
        eval (s.gsub /(\d+)?[dD](\d+)/ do
            n = $1 ? $1.to_i : 1
            n.times { n += rand $2.to_i }
            n
        end)
    end
    

提交回复
热议问题