Similar Problems

Similar Problems not available

Dice Roll Simulation - Leetcode Solution

Companies:

LeetCode:  Dice Roll Simulation Leetcode Solution

Difficulty: Hard

Topics: dynamic-programming array  

Problem Statement:

You have a standard dice that is 6-sided. You are asked to simulate a dice roll using a random number generator. Write a function to generate a random integer in the range of 1 to 6.

Solution:

Approach 1: Using the built-in random module of Python

Python has a built-in random module that provides functions for generating random numbers. We can use the randint function in the random module to generate a random integer in the given range. Here is the Python function to simulate a dice roll:

import random

def rollDice():
  return random.randint(1, 6)

This function uses the randint function of the random module to generate a random integer in the range of 1 to 6. The function returns the generated integer as the result.

Approach 2: Using the numpy module of Python

Numpy is a third-party library for Python that provides support for arrays and numerical mathematics. We can use the randint function in the numpy module to generate a random integer in the given range. Here is the Python function to simulate a dice roll using numpy:

import numpy as np

def rollDice():
  return np.random.randint(1, 7)

This function uses the randint function of the numpy module to generate a random integer in the range of 1 to 6. The function returns the generated integer as the result.

Approach 3: Using the random number generator of C++

If we want to simulate a dice roll in a C++ program, we can use the random number generator of the C++ standard library. Here is the C++ function to simulate a dice roll:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int rollDice() {
    srand(time(0));
    return (rand() % 6) + 1;
}

int main() {
    cout << "Dice roll result: " << rollDice() << endl;
    return 0;
}

This function uses the srand function to seed the random number generator with the current time. The rand function is then used to generate a random integer in the range of 0 to 5. We add 1 to the result to get the final result in the range of 1 to 6. The function returns the generated integer as the result.

Dice Roll Simulation Solution Code

1