5 kyu

RPG dice roller

126 of 291ankr

Description:

The die is cast!

Your task in this kata is to write a "dice roller" that interprets a subset of dice notation.

Description

In most role-playing games, die rolls required by the system are given in the form AdX. A and X are variables, separated by the letter d, which stands for die or dice.

  • A is the number of dice to be rolled (usually omitted if 1).
  • X is the number of faces of each die.

Here are some examples of input:

'd6' => // One 6-sided die
'2d4' => // Two 4-sided dice

Modifiers

As an addition to the above rules the input may also contain modifiers in the form +N or -N where N is an integer.

Here are some examples of input containing modifiers:

'd3+4' => // One 3-sided die plus 4 (will be in range 5 -> 7)
'd3+4-1' => // One 3-sided die plus 4 minus 1 (will be in range 4 -> 6)

Modifiers must be applied after all dice has been summed up.

Output

Your function must support two types of output depending on the second argument; verbose and summed.

Summed output

If the verbose flag isn't set your function should sum up all the dice and modifiers and return the result as an integer.

Verbose output

With the verbose flag your function should return an object/hash containing an array (dice) with all the dice rolls, and a integer (modifier) containing the sum of the modifiers which defaults to zero.

Example of verbose output:

roll('3d7 +3 -2', true) // => { dice: [ 6, 4, 5 ], modifier: 1 }

Invalid input

Here are some examples of invalid inputs:

'' // Empty
{} // Not a string
'abc' // Not dice notation
'2d6+3 abc' // Contains extra bytes
'abc 2d6+3' // Contains extra bytes
'2d6++4' // Invalid modifiers

Additional information

  • Your solution should ignore all whitespace.
  • roll should return false for invalid input.
Regular Expressions
Arrays
Algorithms

Stats:

CreatedDec 26, 2014
PublishedDec 26, 2014
Warriors Trained1013
Total Skips183
Total Code Submissions6259
Total Times Completed291
JavaScript Completions126
Python Completions134
C# Completions39
Total Stars49
% of votes with a positive feedback rating89% of 104
Total "Very Satisfied" Votes86
Total "Somewhat Satisfied" Votes13
Total "Not Satisfied" Votes5
Total Rank Assessments25
Average Assessed Rank
5 kyu
Highest Assessed Rank
4 kyu
Lowest Assessed Rank
6 kyu
Ad
Contributors
  • ankr Avatar
  • ZozoFouchtra Avatar
  • zebulan Avatar
  • ChristianECooper Avatar
  • brunolm Avatar
  • tachyonlabs Avatar
  • hobovsky Avatar
Ad