• 0

Random Dice Roll Challenge

Problem description :

Write a javascript function that accepts a string argument in the format {digit}d{digit}; where

  • The first digit represents the number of dices.
  • The second digit represents the number of sides.
    The returned value would be the sum of the dice.

For example, if the string argument was 1d6, I would expect a resulting random number 1-6. If the argument was 3d6, 3 six sided dice would be rolled with the result being a random number 3-18.

  • The function must be able to roll dice for any number of sides (2-100).
  • The function must be able to roll any number of dice (1-1000).
  • The function return the sum of the dice.
  • Your code must handle and sanitize bad user input gracefully.

Input : A string // 1d6
Output : A number // One possible output 6

Logic :

  • If the input string is valid
    • Then parse the input string and get the number of sides for a dice and number of dices.
    • Else warn the user and exit the function.
  • Find out the given numbers are in the specified range. If not then warn the user and exit the function.
  • If not then iterate over the number of dices
    • Generate a random number in the range of number od sides and sum those numbers.

Solution :