227k views
25 votes
1. Create a Java program.

2. The class name for the program should be 'RandomDistributionCheck'.
3. In the main method you should perform the following:
a. You should generate 10,000,000 random numbers between 0 - 19.
b. You should use an array to hold the number of times each random number is generated.
c. When you are done, generating random numbers, you should output the random number, the number of times it occurred, and the percentage of all occurrences. The output should be displayed using one line for each random number.
d. Use named constants for the number of iterations (10,000,000) and a second named constant for the number of unique random numbers to be generated (20).

User Denikov
by
6.0k points

1 Answer

8 votes

Answer:

In Java:

import java.util.*;

public class RandomDistributionCheck{

public static void main(String[] args) {

final int iter = 10000000;

final int unique = 20;

Random rd = new Random();

int [] intArray = new int[20];

for(int i =0;i<20;i++){ intArray[i]=0; }

for(int i =0; i<iter; i++){

int rdd = rd.nextInt(20);

intArray[rdd]++; }

System.out.println("Number\t\tOccurrence\tPercentage");

for(int i =0;i<unique;i++){

System.out.println(i+"\t\t"+intArray[i]+"\t\t"+(intArray[i]/100000)+"%");

} } }

Step-by-step explanation:

This declares the number of iteration as constant

final int iter = 10000000;

This declares the unique number as constant

final int unique = 20;

This creates a random object

Random rd = new Random();

This creates an array of 20 elements

int [] intArray = new int[20];

This initializes all elements of the array to 0

for(int i =0;i<20;i++){ intArray[i]=0; }

This iterates from 1 to iter

for(int i =0; i<iter; i++){

This generates a random number

int rdd = rd.nextInt(20);

This increments its number of occurrence

intArray[rdd]++; }

This prints the header

System.out.println("Number\t\tOccurrence\tPercentage");

This iterates through the array

for(int i =0;i<unique;i++){

This prints the required output

System.out.println(i+"\t\t"+intArray[i]+"\t\t"+(intArray[i]/100000)+"%");

}

User Stoycho Andreev
by
5.6k points