Why am I getting this error in my JAVA code? - java

The birthday paradox says that the probability that two people in a room
will have the same birthday is more than half as long as the number of
people in the room (n), is more than 23. This property is not really a paradox,
but many people find it surprising. Design a C++ program that can
test this paradox by a series of experiments on randomly generated birthdays,
which test this paradox for n =5, 10, 15, 20, . . . , 100. You should run
at least 10 experiments for each value of n and it should output, for each
n, the number of experiments for that n, such that two people in that test
have the same birthday.
package birth;
import java.util.Random;
/* Question:
The birthday paradox says that the probability that two people in a room
will have the same birthday is more than half as long as the number of
people in the room (n), is more than 23. This property is not really a paradox,
but many people find it surprising. Design a C++ program that can
test this paradox by a series of experiments on randomly generated birthdays,
which test this paradox for n =5, 10, 15, 20, . . . , 100. You should run
at least 10 experiments for each value of n and it should output, for each
n, the number of experiments for that n, such that two people in that test
have the same birthday.
*/
public class birth {
public static final int YEAR = 365;
public static void main(String[] args)
{
int numOfPeople = 5;
int people = 5;
//DOB array
int[] birthday = new int[YEAR];
//Creates an array that represents 365 days
for (int i = 0; i < birthday.length; i++)
birthday[i] = i + 1;
//Random Number generator
Random randNum = new Random();
int iteration = 1;
//iterates around peopleBirthday array
while (numOfPeople <= 100)
{
System.out.println("Iteration: " + iteration);
System.out.println();
//Creates array to holds peoples birthday
int[] peopleBirthday = new int[numOfPeople];
//Assigns people DOB to people in the room
for (int i = 0; i < peopleBirthday.length; i++)
{
int day = randNum.nextInt(YEAR + 1);
peopleBirthday[i] = birthday[day];
}
for (int i = 0; i < peopleBirthday.length; i++)
{
//stores value for element before and after
int person1 = peopleBirthday[i];
int person2 = i + 1;
//Checks if people have same birthday
for (int j = person2; j < peopleBirthday.length; j++)
{
//Prints matching Birthday days
if (person1 == peopleBirthday[j])
{
System.out.println("P1: " + person1 + " P2: " + peopleBirthday[j]);
System.out.println("Match!!! \n");
}
}
}
//Increments the number of people in the room
numOfPeople += 5;
iteration++;
}
}
}
I am getting a error: java.lang.ArrayIndexOutOfBoundsException: 365 I can't figure out what is wrong with my code

It would be nice if you provided the exact line number where the exception was thrown (the information is in the error stack trace that you got), but it's very likely that the problem occurs here:
int day = randNum.nextInt(YEAR + 1); // 365 + 1 = 366
peopleBirthday[i] = birthday[day];
The documentation for Random.nextInt says:
Returns: the next pseudorandom, uniformly distributed int value between zero (inclusive) and bound (exclusive) from this random number generator's sequence.
In this case, you are calling Random.nextInt with a value of 366 (365 + 1), so that means that you are effectively reading some random number between 0 and 365. If you ever do get 365, that will make birthday[day] throw the out of bounds exception, as the maximum index of your array is 364, not 365.
You probably meant to read the random value this way instead:
int day = randNum.nextInt(YEAR); // 365 (exclusive)

Arrays in Java are zero based. If you create birthday with a length of 365, the indexes would be from 0 to 364.
You need to change this line from this:
int[] birthday = new int[YEAR];
To this:
int[] birthday = new int[YEAR+1];

Related

My Birthday Problem code is not printing anything

I am an absolute beginner to learning programming and I was given this assignment:
Birthday problem. Suppose that people enter a room one at a time. How people must enter until two share a birthday? Counterintuitively, after 23 people enter the room, there is approximately a 50–50 chance that two share a birthday. This phenomenon is known as the birthday problem or birthday paradox.
Write a program Birthday.java that takes two integer command-line arguments n and trials and performs the following experiment, trials times:
Choose a birthday for the next person, uniformly at random between 0 and n−1.
Have that person enter the room.
If that person shares a birthday with someone else in the room, stop; otherwise repeat.
In each experiment, count the number of people that enter the room. Print a table that summarizes the results (the count i, the number of times that exactly i people enter the room, and the fraction of times that i or fewer people enter the room) for each possible value of i from 1 until the fraction reaches (or exceeds) 50%.
For more information on the assignment
However, my code won't print. I would really appreciate if someone could help me find the problem to my assignment.
public class Birthday {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]); //number of days
int trials = Integer.parseInt(args[1]);
boolean[] birthdays = new boolean[n];
int[] times = new int[n + 2]; //number of times i people entered the room
int r;
for (int t = 1; t <= trials; t++) {
for (int k = 0; k < n; k++) { //reset birthday
birthdays[k] = false;
}
for (int i = 1; i <= n; i++) { //number of times
r = (int) (Math.random() * (n - 1)); //random birthday
if (birthdays[r] = false) {
birthdays[r] = true;
continue;
}
else if (birthdays[r] = true) {
times[i]++; //number of times i people entered the room + 1
break;
}
}
}
int j = 1;
while ((double) times[j] / trials <= 0.5) {
System.out.print(j + "\t" + times[j] + "\t" + ((double) times[j] / trials));
j++;
System.out.println("");
}
}
}
I can spot two errors from your code
As Scary Wombat pointed out, you are miss double equal sign inside of your if statement.
The assignment is asking you to calculate "fraction of times that i or fewer people enter the room", meaning you need to do a summation for the first i indices and divided by trials.
For example, among 1 million trials, the fraction in which first duplicate birthday happens when 4th person enters is
(times[0] + times[1] + times[2] + times[3])/ 1000000
Here is what I got:
1 0 0.0
2 2810 0.00281
3 5428 0.008238
4 8175 0.016413
As you can see the fraction is calculated by adding the first three elements together and then divided by 1000000 (2810 + 5428 + 8175 = 16413) / 1000000 = 0.016413
The way you are calculating the fraction ((double) times[j] / trials) is not correct.
You are not adding the previous counts as shown in the example. To do so, you can create a new variable to store the sums of previous counts. and use it as your while loop condition. For instance, see below..
csum += times[j]; // this adds the previous counts into a cumulative sum.
This cumulative sum is supposed to be the one u use to divide by trials to get your probability. Cheers!

Java Assignment, lost on the math

I am really hoping you can help me out. I am completely lost in my assignemnt and I have been in touch with my instructor, but I still do not understand how to approach my problem. The assignment states I need:
Current Maximum of all generated random numbers so far.
(Utilize Math class to determine current Max)
Current Minimum of all generated random numbers so far.
(Utilize Math class to determine current Min)
I know I need these where I currently have Math.max & Math.min at the lower end of my code. I just am clueless on how to implement it and what the numbers represent.
import java.util.Scanner;
public class CLASS {
public static void main(String[] args) {
Scanner stdln = new Scanner(System.in);
final String HEADING_STR = "%-15s%-15s%-15s%-15s%-15s%-15s\n";
final String DATA_STR = "%-15s%-15.0f%-15s%-15s%-15s%-15s\n";
String maxRandomNumberStr; // The maximum random number to be computed (an integer to be parsed)
String amountRandomNumbersStr; // The amount of random numbers to be generated (an integer to be parsed)
int maxRandomNumber; // the integer of maxRandomNumberStr
int amountRandomNumbers; // the integer of amountRandomNumbersStr
int round = 0; // the first round
//int theMax = 0; // how to use?
//int theMin = 0; // how to use?
System.out.print("Please enter the maximum random number to be used: ");
maxRandomNumberStr = stdln.nextLine();
maxRandomNumber = Integer.parseInt(maxRandomNumberStr);
System.out.print("Please enter the number of rounds: ");
amountRandomNumbersStr = stdln.nextLine();
amountRandomNumbers = Integer.parseInt(amountRandomNumbersStr);
System.out.printf (HEADING_STR, "Round", "Round #", "Curr Max", "Curr Min", "Curr Total", "Curr Avg");
for (int i=1; i<=amountRandomNumbers; i++) {
System.out.printf(DATA_STR, round += 1, (Math.random()*(maxRandomNumber)), Math.max(?,?), Math.min(?,?), "1", "1"); // the "1"s are placeholders
}
} // end main
} // end CLASS
If I am understanding your problem correctly I think your input for Math.max() and .min() would be the newest random number being compared to the old min/max. Please see the Math class documentation here: http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html
I think you would need to always save any new maximum/minimum variables and compare them to the new random number each time.
int theMax = 0;
theMax = Math.max(newRandomNumber, theMax);
This will assign theMax to be the highest of the two numbers.
You can do the same for min.
Good luck.
If you're using Java 8, you ca do it easily with a Stream.
Stream.of(random1, random2, ...).max();
Stream.of(random1, random2, ...).min();
Stream.of(random1, random2, ...).avg();

Rolling m die with n sides x times

Okay so I changed my code around and deleted a lot of the unnecessary garbage in it. It works for some numbers but not for others, for example, when I put in 100 rolls/8 sides/3 die it gives me an out of bounds error despite the limits I've set for it. Obviously I've looked over some detail, I'm just not sure what detail it is.
public class Ass11f {
public static void main(String[] args) {
EasyReader console = new EasyReader();
System.out.print("Enter how many times you want to roll the die: ");
int numRolls = console.readInt();
System.out.print("Enter the amount of sides: ");
int numSides = console.readInt();
System.out.print("Enter the amount of die: ");
int numDie = console.readInt();
int[] rollSum = new int[numDie*numSides];
for (int i = 0; i<numRolls; ++i)
{
int rollCounter=0;
for (int l = 0; l<numDie; ++l){
rollCounter += ((int)(Math.random()*numSides)+1);
}
rollSum[rollCounter]++;
}
for (int m = 2;m<=rollSum.length;++m) System.out.println(m+"'s: "+rollSum[m]+" times, "+((((double)rollSum[m])/numRolls)*100)+"%");
}
}
There are two base problems:
When adding roll totals, you're trying to add the maximum roll in an index one past the end of the array. The easy fix is to simply add 1 to the length of your array.
When printing, you cannot access an array using an index equal to the array's length, which is what m<=rollSum.length will eventually do. Replace that with m < rollSum.length so it stops before the final value.
Also, here's some ways to make your array creation a bit clearer:
// The minimum value is always numDie.
// The maximum is always numDie * numSides
// There are maximum - minimum + 1 possible values (ie 6 on a d6)
int maximum = numDie * numSides;
int minimum = numDie;
// Remember, index zero is now the minimum roll.
// The final index is the maximum roll. So the count at an index is really
// the count for any roll with value index + minimum
int[] rollSum = new int[maximum - minimum + 1];
I also recommend splitting up that print statement. It's a bit easier to read and debug. Also, you can start at numDie instead of 2 to account for when you have more or less die than 3:
for (int i = numDie; i < rollSum.length; ++i) {
// Print the first bit, ie "2's: ".
System.out.print(i + "'s: ");
// How many times was that value rolled?
System.out.print(rollSum[i] + " times, ");
// What percentage is that?
double percentage = ((double)rollSum[i]) / numRolls * 100;
System.out.println(percentage + "%");
}

Java Prime Numbers

I am trying to make a prime number list. I have coded it, but it only tells me that the prime numbers of 1 - 100 is 1. I am not sure why that is happening. I also want to make a JFrame for it.
import javax.swing.JOptionPane;
public class ProgrammingAssignment7 {
public static void main(String[] args) {
//Scanner Scan = new Scanner (System.in);
//DECLARE VARIABLES
int x = 1;
int i = 1;
int iNumber = 1;
boolean bNotPrime = false;
boolean bIsPrime = true;
int iNumberToTest;
int iPrimeCheck;
int iCounter;
int iResult = 1;
int iFact = 1;
int iLimit = 100;
String OutputStr = null;
System.out.println("Prime numbers between 1 and " + iLimit);
//loop through the numbers one by one
for(i=1; i < 100; i++) {
bIsPrime = true;
//check to see if the number is prime
for(int j = 2; j < i ; j++) {
if(i % j == 0) {
bIsPrime = false;
break;
}
}
}
// print the number
if(bIsPrime) {
OutputStr = "The Prime Numbers of 1 - 100 are: " + i + "\n";
}
JOptionPane.showMessageDialog(null, OutputStr, "PRIME NUMBERS", JOptionPane.INFORMATION_MESSAGE);
//System.out.print(i + "\n" );
System.exit(0);
}
}
You are calling system.exit(0) in your for loop. So that it will terminate the program after the first iteration. Remove that line and then try to run program. It will give you correct results.
Besides fixing your code you should also fix your algorithm. You are using an algorithm called trial division, which will be uncomfortably slow as your limit increases. Instead, you should use an algorithm called the Sieve of Eratosthenes, invented over two thousand years ago and still widely used today. Here is pseudocode for a simple version of the Sieve of Eratosthenes; I'll leave it to you to translate to Java:
function primes(n)
sieve := makeArray(2..n, True)
for p from 2 to n step 1
if sieve[p]
output p
for i from p * p to n step p
sieve[i] := False
Eratosthenes' algorithm begins by making a list of numbers form 2 to the maximum desired prime n, then enters an iterative phase. At each step, the smallest uncrossed number that hasn't yet been considered is identified, and all multiples of that number, starting from its square, are crossed out; this is repeated until no uncrossed numbers remain unconsidered. All the numbers that remain uncrossed are prime. The inner loop starts at p * p because any smaller composites must have already been crossed out by smaller primes.
For example, to find the primes less than thirty, first report that 2 is prime and cross out 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26 and 28. Then 3 is uncrossed, so report it as prime and cross out 9, 12, 15, 18, 21, 24, and 27. Since 4 has been crossed out, the next uncrossed number is 5, so report it as prime and cross out 25. Finally, since 7 * 7 is greater than 30, the inner loop stops executing and the outer loop collects the rest of the primes: 7, 11, 13, 17, 19, 23 and 29.
If you're interested in programming with prime numbers, I modestly recommend an essay at my blog, which among other things provides an optimized version of the Sieve of Eratosthenes.
In the inner loop, it is enough to iterate to the SQRT(N) instead of N. It can reduces a runtime a bit.
for(int j = 2; j < Math.sqrt(i) ; j++) {
}
Smart algorithm for writing out prime numbers from 1-100 (and also 1- [how many you want] - if you change 100 for another number). Prime numbers can be divisible only by two numbers: 1 and itself, so k have to be equals or less than 2.
for (int i=1; i<=100; i++) {
int k = 0;
for (int j=1; j<=i; j++ ) {
if (i % j == 0) {
k++;
}
}
if (k <= 2) {
System.out.println(i);
}
}

In Java finding numbers that are both a Triangle Number and a Star Number

This is the question I've been assigned:
A so-called “star number”, s, is a number defined by the formula:
s = 6n(n-1) + 1
where n is the index of the star number.
Thus the first six (i.e. for n = 1, 2, 3, 4, 5 and 6) star numbers are: 1, 13, 37,
73, 121, 181
In contrast a so-called “triangle number”, t, is the sum of the numbers from 1 to n: t = 1 + 2 + … + (n-1) + n.
Thus the first six (i.e. for n = 1, 2, 3, 4, 5 and 6) triangle numbers are: 1, 3, 6, 10, 15, 21
Write a Java application that produces a list of all the values of type int that are both star number and triangle numbers.
When solving this problem you MUST write and use at least one function (such as isTriangeNumber() or isStarNumber()
or determineTriangeNumber() or determineStarNumber()). Also you MUST only use the formulas provided here to solve the problem.
tl;dr: Need to output values that are both Star Numbers and Triangle Numbers.
Unfortunately, I can only get the result to output the value '1' in an endless loop, even though I am incrementing by 1 in the while loop.
public class TriangularStars {
public static void main(String[] args) {
int n=1;
int starNumber = starNumber(n);
int triangleNumber = triangleNumber(n);
while ((starNumber<Integer.MAX_VALUE)&&(n<=Integer.MAX_VALUE))
{
if ((starNumber==triangleNumber)&& (starNumber<Integer.MAX_VALUE))
{
System.out.println(starNumber);
}
n++;
}
}
public static int starNumber( int n)
{
int starNumber;
starNumber= (((6*n)*(n-1))+1);
return starNumber;
}
public static int triangleNumber( int n)
{
int triangleNumber;
triangleNumber =+ n;
return triangleNumber;
}
}
Here's a skeleton. Finish the rest yourself:
Questions to ask yourself:
How do I make a Triangle number?
How do I know if something is a Star number?
Why do I only need to proceed until triangle is negative? How can triangle ever be negative?
Good luck!
public class TriangularStars {
private static final double ERROR = 1e-7;
public static void main(String args[]) {
int triangle = 0;
for (int i = 0; triangle >= 0; i++) {
triangle = determineTriangleNumber(i, triangle);
if (isStarNumber(triangle)) {
System.out.println(triangle);
}
}
}
public static boolean isStarNumber(int possibleStar) {
double test = (possibleStar - 1) / 6.;
int reduce = (int) (test + ERROR);
if (Math.abs(test - reduce) > ERROR)
return false;
int sqrt = (int) (Math.sqrt(reduce) + ERROR);
return reduce == sqrt * (sqrt + 1);
}
public static int determineTriangleNumber(int i, int previous) {
return previous + i;
}
}
Output:
1
253
49141
9533161
1849384153
You need to add new calls to starNumber() and triangleNumber() inside the loop. You get the initial values but never re-call them with the updated n values.
As a first cut, I would put those calls immediatly following the n++, so
n++;
starNumber = starNumber(n);
triangleNumber = triangleNumber(n);
}
}
The question here is that "N" neednt be the same for both star and triangle numbers. So you can increase "n" when computing both star and triangle numbers, rather keep on increasing the triangle number as long as its less the current star number. Essentially you need to maintain two variable "n" and "m".
The first problem is that you only call the starNumber() method once, outside the loop. (And the same with triangleNumber().)
A secondary problem is that unless Integer.MAX_VALUE is a star number, your loop will run forever. The reason being that Java numerical operations overflow silently, so if your next star number would be bigger than Integer.MAX_VALUE, the result would just wrap around. You need to use longs to detect if a number is bigger than Integer.MAX_VALUE.
The third problem is that even if you put all the calls into the loop, it would only display star number/triangle number pairs that share the same n value. You need to have two indices in parallel, one for star number and another for triangle numbers and increment one or the other depending on which function returns the smaller number. So something along these lines:
while( starNumber and triangleNumber are both less than or equal to Integer.MAX_VALUE) {
while( starNumber < triangleNumber ) {
generate next starnumber;
}
while( triangleNumber < starNumber ) {
generate next triangle number;
}
if( starNumber == triangleNumber ) {
we've found a matching pair
}
}
And the fourth problem is that your triangleNumber() method is wrong, I wonder how it even compiles.
I think your methodology is flawed. You won't be able to directly make a method of isStarNumber(n) without, inside that method, testing every possible star number. I would take a slightly different approach: pre-computation.
first, find all the triangle numbers:
List<Integer> tris = new ArrayList<Integer>();
for(int i = 2, t = 1; t > 0; i++) { // loop ends after integer overflow
tris.add(t);
t += i; // compute the next triangle value
}
we can do the same for star numbers:
consider the following -
star(n) = 6*n*(n-1) + 1 = 6n^2 - 6n + 1
therefore, by extension
star(n + 1) = 6*(n+1)*n + 1 = 6n^2 + 6n +1
and, star(n + 1) - star(n - 1), with some algebra, is 12n
star(n+1) = star(n) + 12* n
This leads us to the following formula
List<Integer> stars = new ArrayList<Integer>();
for(int i = 1, s = 1; s > 0; i++) {
stars.add(s);
s += (12 * i);
}
The real question is... do we really need to search every number? The answer is no! We only need to search numbers that are actually one or the other. So we could easily use the numbers in the stars (18k of them) and find the ones of those that are also tris!
for(Integer star : stars) {
if(tris.contains(star))
System.out.println("Awesome! " + star + " is both star and tri!");
}
I hope this makes sense to you. For your own sake, don't blindly move these snippets into your code. Instead, learn why it does what it does, ask questions where you're not sure. (Hopefully this isn't due in two hours!)
And good luck with this assignment.
Here's something awesome that will return the first 4 but not the last one. I don't know why the last won't come out. Have fun with this :
class StarAndTri2 {
public static void main(String...args) {
final double q2 = Math.sqrt(2);
out(1);
int a = 1;
for(int i = 1; a > 0; i++) {
a += (12 * i);
if(x((int)(Math.sqrt(a)*q2))==a)out(a);
}
}
static int x(int q) { return (q*(q+1))/2; }
static void out(int i) {System.out.println("found: " + i);}
}

Categories