Find the average of three random numbers - java

I am trying to generate three random integers between 0 and 50, calculate the average, and print the result.
This is what I have so far:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package random.numbers;
import java.util.Random;
/**
*
* #author ericl_000
*/
public class RandomNumbers {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Random rand = new Random ();
int RandNum = 0;
for(int i =0; i < 3; i++)
{
RandNum = rand.nextInt(50);
System.out.println(RandNum);
}
int average = (RandNum);
System.out.println(average);
}
}
The output has the 3 random numbers, but the average is the last number of those 3 numbers. I don't know how to get the average of these 3 numbers. (I am new with Java.)

Your logic for calculating average is not correct, logic for average is:
average = (num1+num2+num3+... .... +num N)/N
So your logic for code should be:
Random rand = new Random();
int RandNum = 0;
float average = 0;
for(int i =0; i < 3; i++)
{
RandNum = rand.nextInt(50);
System.out.println(RandNum);
average = average+RandNum;
}
average = average/3;
System.out.println(average);

Example Code:
import java.util.Random;
public class RandomNumbers {
public static void main (String [] args) {
Random rand = new Random();
int randomNum = 0, total = 0;
int count = 3;
for(int i = 0; i < count; i++)
{
// This gives you 0 to 49, does not include 50!
randomNum = rand.nextInt(50);
System.out.println(randomNum);
// Keep track of total
total += randomNum;
}
// Average is well, total divided by count
int average = total / count;
System.out.printf("Average (Integer division): %d%n", average);
// Using double
double averageDouble = total / ((double) count);
System.out.printf("Average (Double division): %7.3f%n", averageDouble);
}
}
Output:
3
26
8
Average (Integer division): 12
Average (Double division): 12.333
Note:
Using integer or double for division will give u different results!
random#nextInt(int n) gives you a value between 0 (inclusive) and the specified value (exclusive), i.e. nextInt(50) will give you 0 to 49.

and how would you compute the average in real life? You add the numbers up, and you divide by 3.
int sum=0;
for(i=0; i<3; i++)
sum += rand.nextInt(50);
System.out.println(sum/3.0);

You are not saving the random numbers as they are generated.
for(int i =0; i < 3; i++)
{
RandNum = rand.nextInt(50);
System.out.println(RandNum);
}
For each iteration of the loop, a random number is generated and printed.
But is nowhere saved.Then how can you access them later to calculate the average.
Try something like this
for(int i =0; i < 3; i++)
{
RandNum += rand.nextInt(50);
}
This will add generated random number to already generated one.So bascially
RandNum will contain the sum at the end of all iterations of the loop.
Then you can use the following to print the average.
System.out.println(RandNum/3);
Just by naming a variable 'average', it wont find the average.You have to do the necessary calculation.ie.(sum/n).

Not sure why this is a complicated problem.
import java.util.Random;
public class RandomNumbers {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Random rand = new Random ();
int randCount = 3, randNum = 0, total = 0;
for(int i =0; i < randCount; i++) {
randNum = rand.nextInt(50);
System.out.println(randNum);
total = total + randNum;
}
int average = total/randCount;
System.out.println(average);
}
}

The average formula is the sum of all the numbers in a list divided by number by the number of items in that list. You can do this by constantly adding the random numbers up into a variable, lets call it x, then divide that by 3 (total number of items in that list).
for(int i =0; i < 3; i++)
{
RandNum = rand.nextInt(50);
System.out.println(RandNum);
int x += RandNum; //the += sign adds the current value of x to the value of RandNum
}
int average = (x/3);
System.out.println(average);
This answer assumes that you will be only using 3 random numbers.This is using ints however you should probably use doubles considering most averages aren't exact integers:
double RandNum = 0;
for(int i =0; i < 3; i++)
{
RandNum = rand.nextDouble(50);
System.out.println(RandNum);
double x += RandNum; //the += sign adds the current value of x to the value of RandNum
}
double average = (x/3);
System.out.println(average);

import java.util.Random;
public class RandomNumbers {
public static void main(String[] args) {
Random rand = new Random ();
int RandNum = 0;
int[] numbers = new int[]{rand.nextInt(50),rand.nextInt(50),rand.nextInt(50)};
double sum = 0;
for(int i =0; i < 3; i++)
{
System.out.println(numbers[i]);
}
for(int i=0; i < numbers.length ; i++)
sum = sum + numbers[i];
double average = sum / numbers.length;
System.out.println("Average value of array elements is : " + average);
}
}

Related

find probability of n people in a class of x share the same birthday using monte carlo simulation in java

As the problem states, i must use monte carlo(randomness) to solve the question given. I am running the simulation 1,000,000 times.
import java.util.*;
public class MonteCarlo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter size of the class: ");
int classSize = sc.nextInt();
System.out.println("Please enter the amount of people who share the same birthday: ");
int birthPpl = sc.nextInt();
System.out.println("calculate the probability that "+birthPpl+" people share the same Birthday in a class size of "+classSize);
sc.close();
int birthdays [] = new int[classSize];
int simulations = 0;
int success=0;
for(int i=0; i<1000000; i++){
simulations++;
if(Collision(birthdays)>=birthPpl){
success++;
}
}
System.out.println(success+" "+simulations);
System.out.println("Answer: "+ (success*100)/simulations + "%");
}
public static int Collision(int birthday[]){
Random rand = new Random();
for(int i=1; i<birthday.length; i++){
birthday[i]= rand.nextInt(365);
}
int count = 0;
for(int i=0; i<birthday.length; i++){
for(int j= i+1; j<birthday.length; j++){
if(birthday[i]==birthday[j]){
count++;
}
}
}
return count;
}
}
As per a couple of psuedo code solutions i have seen online i have tried looping through the size of the class x and inserting in a random birthday. then comparing birthdays , reducing the birthdays i look through by 1 each time. I then check the number of collisions against the amount sof ppl who should a birthday , if it is greater or equal to it than i increase the count. i have been given sample imput 20 and 2 which should give 41 % but my program gives eithe 7 or 8 %
What's the problem, and how can it be fixed?
You could also make use the Random and HashMap classes. Map.merge will take the key, a birthday in this case, then a default value of 1, and continues to add 1 to the existing value which is returned and compared to x. Then success is appropriately updated. The Random class provides a variety of methods to return random numbers and is usually preferred over Math.random.
double success = 0;
int tests = 1_000_000;
// instantiate a Random class for selecting the next birthday
Random r = new Random();
// a map to hold the frequency count of same birthdays
Map<Integer,Integer> birthdays = new HashMap<>();
int n = 23;
int x = 2;
for(int i=0; i< tests; i++) {
for (int j = 0; j < n; j++) {
if (birthdays.merge(r.nextInt(365), 1, Integer::sum) >= x) {
success++;
break;
}
}
// clear the map for the next run
birthdays.clear();
}
Using System.out.printf facilitates formatting the output.
System.out.printf("probability = %4.1f%%%n", (success/tests) * 100);
prints something like the following:
probability = 50.7%
import java.util.Scanner;
public class Birthday {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // class size
int x = sc.nextInt(); // people who share the same birthday
double tests = 1_000_000;
double success = 0;
// fills array of birthdays and breaks out when x amount of people share
// a birthday. then we find the % of successes.
for (int i = 0; i < tests; i++) {
int[] year = new int[365];
for (int j = 0; j < n; j++) {
int birthday = (int) (Math.random() * 365);
year[birthday]++;
if (year[birthday] >= x) {
success++;
break;
}
}
}
System.out.println(Math.round(success * 100 / tests));
}
}

How to sort array in to 'bins', and print out stars for how many numbers are in that bin?

//so basically for all that is below, I'm trying to sort the random numbers that have been generated, and then 'sort' then into bins, and then for how many numbers there are in the bin, a star * will print out for every number. it will look like a histogram at the end. like this:
12 random integers in [0, 10) sorted into 2 bins:
******* 7 0.5833333 [5.0, 10.0)
***** 5 0.41666666 [0.0, 5.0)
but its like its skips that last two methods - generateBins, and printBins. how would i sort the random numbers into bins depending on the number (like above) and print a * for every number in that array bin?
public class BinSort {
final int totalBins;
final int totalRandom;
final float widthBin;
int [] storeNumbers;
int [] binCount;
public BinSort (int nBins, int nSamples, int max) {
totalBins = nBins; //total # of bins, ie 2
totalRandom = nSamples; //total random number generated, ie 12
widthBin = (float) (max/totalBins); ie 2
int [] storeNumbers = new int [max];
for (int i = 0; i < totalRandom-1; i++) {
storeNumbers[i] = Random.rand(i, max);
System.out.println(storeNumbers[i]);
}
}
void generateBins () {
int [] binCount = new int [totalBins];
for (int i=0; i < totalRandom-1; i++) {
int bin = (int)(storeNumbers[i]/ totalBins);
Math.floor(bin);
bin = binCount [i];
}
}
void printBins () {
for (int i = 0; i < binCount.length - 1; i++) {
for (int j=0; j < binCount[j]; j ++) {
System.out.print("*");
System.out.println(); }
float freq = (binCount[i]/totalRandom);
float binMin = (i * widthBin);
float binMax = (binMin * widthBin);
System.out.print(binCount[i] + freq + binMin + binMax);
System.out.println();
}
}
}
In your constructor you have
int [] storeNumbers = new int [max];
The problem here is that this will create a new local variable with the same name as your instance variable, storeNumbers. Also, the size should be totalRandom, not max. You need to create a Random object that you'll use to generate random numbers. Putting this together we get:
public BinSort (int nBins, int nSamples, int max) {
totalBins = nBins; //total # of bins, ie 2
totalRandom = nSamples; //total random number generated, ie 12
widthBin = (float) (max/totalBins); //ie 2
storeNumbers = new int [totalRandom];
Random rand = new Random();
for (int i = 0; i < totalRandom; i++) {
storeNumbers[i] = rand.nextInt(max);
}
}
This will generate totalRandom random numbers between 0 and max(exclusive) and store them the instance variable storeNumbers.
Next, in generateBins you have the same issue with
int [] binCount = new int [totalBins];
Which again will hide your instance variable binCount. The bin that a storeNumber falls into will be given by (int)(storeNumbers[i] / widthBin), and you need to increment the resulting bin by 1.
void generateBins()
{
binCount = new int[totalBins];
for (int i = 0; i < totalRandom; i++)
{
int bin = (int)(storeNumbers[i] / widthBin);
binCount[bin] += 1;
}
}
Finally, to the printing of the bins. This line
for (int j=0; j < binCount[j]; j ++)
should be
for (int j=0; j < binCount[i]; j ++)
Also, you should use printf to format the numbers you want to print.
void printBins()
{
for (int i = 0; i < binCount.length; i++)
{
for (int j = 0; j < binCount[i]; j++)
{
System.out.print("*");
}
float freq = (float)binCount[i] / totalRandom;
float binMin = i * widthBin;
float binMax = (i+1) * widthBin;
System.out.printf(" %d %.3f %.3f %.3f\n", binCount[i], freq, binMin, binMax);
}
}
Test:
public static void main(String[] args)
{
BinSort bs = new BinSort(2, 12, 10);
bs.generateBins();
bs.printBins();
}
Output:
***** 5 0.417 0.000 5.000
******* 7 0.583 5.000 10.000
Which I think is what you were looking for.
Be sure to compare your original code with the changes above and make sure you understand what the issues were and why the changes work.

How to sort this array into ascending order?

I would like to generate an array of 100 numbers and find their average and sum. I am able to do this but I am not able to get the output of numbers into ascending order. I am super new to Java.
import java.util.Random;
public class randomNumberGen
{
public static void main(String [] args)
{
Random r=new Random();
double sum = 0; // is double so to prevent int division later on
int amount = 100;
int upperBound = 100;
for (int i = 0; i < amount; i++){
int next = r.nextInt(upperBound) + 1; // creates a random int in [1,100]
System.out.println(next);
sum += next; // accumulate sum of all random numbers
}
System.out.println("Your average is: " + (sum / amount));
System.out.println("Your sum is: " + (sum));
}
}
it is very easy. however I didn't see any array in your code. I create an example code for you. you can ask for more help.
public static void main(String[] args) {
SecureRandom random = new SecureRandom(); // it is better to use this library
double sum = 0; // is double so to prevent int division later on
int amount = 100;
int upperBound = 100;
int[] array = new int[amount]; // create an array with amount size
for (int i = 0; i < amount; i++) {
array[i] = random.nextInt(upperBound) + 1; // creates a random int in [1 , upperBound]
sum += array[i]; // accumulate sum of all random numbers
}
Arrays.sort(array); // sort array in default order which is ascending
System.out.println(Arrays.toString(array)); // toString is a way to print all of array, without iterate it and print it
System.out.println("Your average is: " + (sum / amount));
System.out.println("Your sum is: " + sum);
}
There are a lot of different sorting methods. For a beginner start with either Bubble Sort or Insertion Sort. Insertion Sort is slightly better as on average it runs slightly faster.
I offer to use one of special collections to sort numbers internally, without using one of sorting algorithms (e.g. us PriorityQueue):
public static void main(String[] args) {
final int amount = 100;
Random random = new SecureRandom();
Queue<Integer> queue = new PriorityQueue<>(amount, Comparator.naturalOrder()); // Comparator.reverseOrder() for reverse order
int sum = 0;
for (int i = 0; i < amount; i++) {
int val = random.nextInt(100) + 1;
sum += val;
queue.add(val);
}
System.out.println(Arrays.toString(queue.toArray()));
System.out.println("Your average is: " + (double)sum / amount);
System.out.println("Your sum is: " + sum);
}

How to create array in method to print random number desired by user?

I wrote the code to create user desired number of array and size, but there is no any random number displayed.
public class ArrayStats {
public static void fillRandomArray(int [] a, int max) {
int [] randomArray = new int[max];
for (int i=0; i < randomArray.length; i++){
randomArray[i] = (int)(Math.random());
}
}
}
The problem is that Math.random() return a Double value from 0.0 to 1.0
0.1 to int = 0, ....... 0.5 to int = 0 .
If you need generate random number try it:
public static int randomNumber(int min, int max) {
Random rand = new Random();
int num = rand.nextInt(max - min + 1) + min;
return num;
}
public static void fillRandomArray(int [] a, int max) {
int [] randomArray = new int[max];
for (int i=0; i < randomArray.length; i++){
//Example Generate random number between 1 and 9
randomArray[i] = randomNumber(1,9);
}
}
Here's a tiny modification to your code, that would fill your array with random ints from 0 to Integer.MAX_VALUE:
public class ArrayStats {
public static void fillRandomArray(int [] a, int max) {
int [] randomArray = new int[max];
for (int i=0; i < randomArray.length; i++){
randomArray[i] = (int)(Math.random() * Integer.MAX_VALUE);
}
}
}
The thing here is that Math.random() returns a double in the range from 0 to 1. When you were casting it to (int) it always turned 0.
Alternatively you can take a look at class Random.
The random values aren't stored because function Math.random() generates values between 0.0 (inclusive) and 1.0 (exclusive) and hence, cast to int will always return 0. From official docs:
Returns a double value with a positive sign, greater than or equal to
0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.
Either multiply the Math.random() result with some fixed integer value and cast to int or use a Random instance's method random.nextInt() as:
int rand = (int)(Math.random() * FIXED_INT_VAL);
or
Random r = new Random();
int rand = r.nextInt();
The latter approach is recommend due to reason explained in this post.
So, your code becomes:
public class ArrayStats {
public static void fillRandomArray(int [] a, int max) {
int [] randomArray = new int[max];
Random r = new Random();
for (int i=0; i < randomArray.length; i++){
randomArray[i] = r.nextInt();
}
}
}

Average Random Integers

I am trying to write a program that takes an integer as command-line argument, uses random to print N uniform random values between 0 and 1, and then prints their average value.
I'm not sure what arguments to put in the while loop so that random integers are repeated n times, n being the number from the user indicating the number of integers the random has to generate.
Any help would be appreciated.
enter code here
public class UniformRandomNumbers1 {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int i;
double total = 0.0; //(The sum of n, numbers)
for (i = 1; i <= n; i++) {
double rand = Math.random(); //(Random number between 0 & 1)
total += rand; // Increment total by rand
System.out.println(i + " = " + rand); // Prints value of n & corresponding double value
}
double average = total / n; // Calculates average of n numbers
System.out.println("Average = " + average); // Prints average of n numbers, Can i get an up vote? :) plz
}
}
if you just need to execute a loop a specific number of times, I'd use a for loop
The following loop will iterate exactly n times, and It's what I personally use when I need to do something exactly n times.
for(int i=0; i<n; i++)
{
//insert body here
}
int total = 0;
for (int current = 1; current <= n; n++) {
double rand = Math.random();
total += rand;
System.out.println(currentN + "= " + rand);
}
System.out.println("Total = " + total);
under the assumption that your PRNG is behaving correcly you just need this:
main()
{
printf("\n0.5");
exit(0);
}
that's for N sufficiently large... computed in constant time. otherwise use the moving average formula:
http://en.wikipedia.org/wiki/Moving_average
which requires only O(1) memory space instead of the naive O(N) approach
here the cut&paste java code:
public class Rolling {
private int size;
private double total = 0d;
private int index = 0;
private double samples[];
public Rolling(int size) {
this.size = size;
samples = new double[size];
for (int i = 0; i < size; i++) samples[i] = 0d;
}
public void add(double x) {
total -= samples[index];
samples[index] = x;
total += x;
if (++index == size) index = 0; // cheaper than modulus
}
public double getAverage() {
return total / size;
}
}

Categories