Docsity

Java Program for Generating Random Numbers and Counting Occurrences, Study notes of Computer Science

Toggle sidebar
bg1
416-10.1
// Special random class for the hockey problem.
import java.util.*;
public class MyRandom
{
private static Random r=new Random();
// Return a random number with magnitude 1, 2, or 3, and
// the opposite sign from x.
public static int next123(int x)
{
if (x>0)
return -(r.nextInt(3)+1);
else
return r.nextInt(3)+1;
}
}
// Using the special random class.
public class RandomExample
{
public static void main(String[] args)
{
int[] count=new int[7];
for (int i=0;i<count.length;i++)count[i]=0;
int x=1;
for (int i=1;i<=2000;i++)
{
x=MyRandom.next123(x);
System.out.print(x+" "); // Display random number.
if (i%50==0) // New line every 50 values.
System.out.println();
count[x+3]++;
}
// Display results.
for (int i=0;i<7;i++)
System.out.println(i-3+" occured "+count[i]+" times.");
}
}
pf3

Partial preview of the text

Download Java Program for Generating Random Numbers and Counting Occurrences and more Study notes Computer Science in PDF only on Docsity!

// Special random class for the hockey problem.

import java.util.*;

public class MyRandom

private static Random r=new Random();

// Return a random number with magnitude 1, 2, or 3, and

// the opposite sign from x.

public static int next123(int x)

if (x>0)

return -(r.nextInt(3)+1);

else

return r.nextInt(3)+1;

// Using the special random class.

public class RandomExample

public static void main(String[] args)

int[] count=new int[7];

for (int i=0;i<count.length;i++)count[i]=0;

int x=1;

for (int i=1;i<=2000;i++)

x=MyRandom.next123(x);

System.out.print(x+" "); // Display random number.

if (i%50==0) // New line every 50 values.

System.out.println();

count[x+3]++;

// Display results.

for (int i=0;i<7;i++)

System.out.println(i-3+" occured "+count[i]+" times.");

Ï

ÏϧÏ-3 occured 323 times. ÏϧÏ-2 occured 344 times. ÏϧÏ-1 occured 333 times. ÏϧÏ0 occured 0 times.

  • §Ï-3 2 -1 2 -1 1 -1 3 -3 2 -3 2 -1 2 -1 1 -1 1 -3 3 -2 3 -1 2 -2 3 -3 2 -1 3 -3 3 -1 2 -2 2 -2 3 -2 1 -2 1 -3 1 -2 3 -1 3 -1
  • ÏϧÏ-1 1 -3 1 -3 3 -3 1 -1 2 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