Evaluate dice rolling notation strings

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

    perl eval version, 72 chars

    sub e{$_=pop;s/(\d+)?d(\d+)/\$a/i;$a+=1+int rand$2-1for 0...$1-1;eval$_}
    

    runs like

    print e("4*d12+3"),"\n";
    

    Based on the ruby solution, can only run once(you should undef $a between runs).

    shorter version, 68 chars, funky (0 based) dice

    sub e{$_=pop;s/(\d+)?d(\d+)/\$a/i;$a+=int rand$2for 0...$1-1;eval$_}
    

    EDIT

    perl 5.8.8 didn't like the previous version, here's a 73 char version that works

    sub e{$_=pop;s/(\d+)?d(\d+)/\$a/i;$a+=1+int rand$2-1for 1...$1||1;eval$_}
    

    70 char version supporting multiple rolls

    sub e{$_=pop;s/(\d*)d(\d+)/$a=$1||1;$a+=int rand$a*$2-($a-1)/ieg;eval}
    

提交回复
热议问题