I want to play Dungeons and Dragons, but I don't have any dice! Your challenge is to roll some D&D dice.
The input format specification in Backus-Naur form is:
<valid-input> ::= <opt-integer> "d" <integer> <opt-modifier>
<opt-integer> ::= | <integer>
<opt-modifier> ::= | "+" <integer>
<integer> ::= "0" | "1" | "2" | "3" | "4" | "5" |
"6" | "7" | "8" | "9" | <integer> <integer>
The optional integer before the d
is the number of dice to roll; it must be at least 1
, and defaults to 1
if not supplied.
The required integer immediately after the d
is the number of sides each die has; it must be at least 1
. The sides of each die are distinct consecutive positive integers starting at 1
.
The optional modifier may be +0
, and it defaults to +0
if not specified.
For example, for the input 2d10+5
, you generate two random numbers from 1 to 10 inclusive, add them together, and add 5. Then you will output the result.
If you receive invalid input, such as 2d
, d20+
, 0d4
, 2d5+1+2
, 2+2
, or anything else that doesn't fit this format, you must output "Invalid input
". Otherwise, you must output only a single random integer, weighted according to the input. For example, 3d6
should produce more 10
s than 4
s.
Test cases
Input Minimum possible output Maximum possible output
d1 1 1
d6 1 6
d1+3 4 4
d20+3 4 23
2d1 2 2
2d6+2 4 14
d01 1 1
d01+0 1 1
01d01+01 2 2
3d20+10 13 70
d Invalid input
d0 Invalid input
d+0 Invalid input
d0+0 Invalid input
0d1 Invalid input
0d1+1 Invalid input
d1+ Invalid input
1d Invalid input
1d1+ Invalid input
1d+1 Invalid input
2d+2d Invalid input
d2+d2 Invalid input
d2+2+2 Invalid input
d2-1 Invalid input
-d2 Invalid input
-2d2 Invalid input
4*3 Invalid input
4*d2 Invalid input
This is code-golf, so the shortest code in bytes will win!
02d05+073
a valid input? \$\endgroup\$n
andp
as optional, but input which choose not to include them (d20+
) as invalid. \$\endgroup\$+
sign should only be added if the modifierp
is provided. \$\endgroup\$1d4+1d6
for a Rogue sneak attacking with a dagger) or having a negativep
(eg,1d20-1
for a skill check with no ranks/training and a negative ability modifier). \$\endgroup\$2d8 + 1d6 + 4
? You're gonna have a bad time \$\endgroup\$