Program to Emulate N Dice Roller
Last Updated :
29 Jul, 2021
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;
srand ((unsigned) time (0));
cout << "Hey Geek! You rolled: " ;
for ( int i = 0; i < numberOfDice ; i++)
{
int randomNumber = ( rand () % 6) + 1;
total += randomNumber;
cout << randomNumber << " " ;
}
cout << "\n"
<< "Total: " << total << "\n" ;
return 0;
}
|
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: " );
Scanner input = new Scanner(System.in);
int numberOfDice = input.nextInt();
Random ranNum = new Random();
System.out.print( "Hey Geek! You rolled: " );
int total = 0 ;
int randomNumber = 0 ;
for ( int i = 0 ; i < numberOfDice; i++) {
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)
Share your thoughts in the comments
Please Login to comment...