In this article, we emulate N Dice roller. Given N, the task is to create a Java program which outputs N random numbers where each number is in the range 1 to 6 inclusive. Such type of emulation can be used in games and apart from that some similar variations of the problem statement can be used in several other applications.
Example1:
Enter the Number of dice: 4 Hey Geek! You rolled: 3 2 1 6 Total: 12
Example2:
Enter the Number of dice: 2 Hey Geek! You rolled: 1 6 Total: 7
Note: The output may change since we are using random numbers.
Approach:
Here, we use the Random object in Java to generate random integers in the range 1 to 6 inclusive and execute a loop to generate such random numbers N times.
Implementation
C++
#include <cstdlib> #include <ctime> #include <iostream> using namespace std; int main() { int numberOfDice, total = 0; cout << "Enter the Number of dice: " ; cin >> numberOfDice; // calling srand() with time() function for seed // generation srand ((unsigned) time (0)); cout << "Hey Geek! You rolled: " ; for ( int i = 0; i < numberOfDice ; i++) { // Generating the random number and storing it // in the 'randomNumber' variable int randomNumber = ( rand () % 6) + 1; total += randomNumber; cout << randomNumber << " " ; } cout << "\n" << "Total: " << total << "\n" ; return 0; } // This code is contributed by anurag31. |
Java
import java.util.Random; import java.util.Scanner; public class Main { public static void main(String args[]) { System.out.print( "Enter the number of dice: " ); // Initializing the Scanner object to read input Scanner input = new Scanner(System.in); int numberOfDice = input.nextInt(); // Initializing the Random object for // generating random numbers Random ranNum = new Random(); System.out.print( "Hey Geek! You rolled: " ); int total = 0 ; int randomNumber = 0 ; for ( int i = 0 ; i < numberOfDice; i++) { // Generating the random number and storing it // in the 'randomNumber' variable randomNumber = ranNum.nextInt( 6 ) + 1 ; total = total + randomNumber; System.out.print(randomNumber); System.out.print( " " ); } System.out.println( "" ); System.out.println( "Total: " + total); input.close(); } } |
Output
Time Complexity: O(N)
Auxiliary Space: O(1)