Java array out bounds can't find the index out of bounds - java

This is an eulers method program and i think i pretty much got it, but i keep getting arrayIndex out of bounds between my x and y arrays and its counter i, I think i know what arrayIndex out of bounds mean but i cant seem to get where the index went out of bounds. Can anyone help?
import java.util.Scanner;
import static java.lang.System.out;
import static java.lang.System.in;
public class INFINITE_EULER {
/**
* #param args
*/
public static float functionof(float b,float c){
return (float) ((float) Math.pow(b+0.1, 2)+ Math.pow(c+0.1, 2)); //to return the function of x and y
}
public static void main(String[] args) {
Scanner myScanner = new Scanner(in);
out.println("Programme to implement Eulers method");
float h;
float y[] = new float[100]; //initialize the value of x from 0 to 100
float x[] = new float[100]; // initialize the value of y from 0 to 100
int i; //variable i is the counter for the array
out.println("enter the value of h");
h = myScanner.nextFloat();
out.println("Enter the first and second interval");
x[0]=myScanner.nextFloat(); //take the value of x0
y[0]=myScanner.nextFloat(); //take the value of y0
for(i = 0 ; i < 100 ; i ++);{ // for x0 to x100
y[i+1] = y[i] + h * Math.abs(functionof(x[i],y[i])); //do yi+1 = yi + h * function of current x and current y through the loop
out.print("y");
out.print(i);
out.print("=");
out.print(y[i]);
}
}
}

Your problem:
in
y[i+1] = y[i] + h * Math.abs(functionof(x[i],y[i])); //do yi+1 = yi + h * function of current x and current y through the loop
when looping
for(i = 0 ; i < 100 ; i ++)
which means
for(i=0 to 99)
y[i+1] -- > when i=99, you will try to acess y[99+1] i.e, y[100] that doesn't exist
EDIT :
change your code to :
for(i = 1 ; i < 100 ; i ++){ // for x1 to x99
y[i] = y[i-1] + h * Math.abs(functionof(x[i-1],y[i-1]));
out.print("y");
out.print(i-1);
out.print("=");
out.print(y[i-1]);
}

Related

Taylor series. Program does fewer iterations

So I am required to recursively calculate e^x using a factored form of a Taylor series:
equation: e^x = 1 +x + (x^2)/2! + ... + ((x^n)/n!))
U(n) = U(n-1)*(x/n)
break point |U(n)| < eps
package lab2;
import java.util.Scanner;
public class Lab2 {
public static void main(String[] args) {
// TODO code application logic here
Scanner in = new Scanner(System.in);
System.out.println("Enter x: ");
int x = in.nextInt();
System.out.println("Enter 0 < e < 1: ");
double e = in.nextDouble();
double result = 1.0;
int n = 1;
double U = x / n;
while (Math.abs(U) >= e)
{
double fa = 1;
for (int i = 1; i <= n; i++)
fa *= i;
result += Math.pow(x, n) / fa;
U *= x / ++n;
}
System.out.println("e^x = " + result);
}
}
It works only x+1 times and then debug says U equals 0 and its our break point. I can't get why this happens. Can you please help me?
Since x and n are integer, dividing them will be done using integer division. Only after the division is down is the result promoted to a double in order to store in U. In order to perform floating point division you could either define x as a double or explicitly cast it when you divide:
double U = ((double) x) / n;

Split an array into four sub-array

Given an array, it contains N element, which are all positive integers; if we can find three elements, and they divide the array into four parts (Notice: the three elements are not contained in any part of the four), and the sum of each part are equal, then we call the array a "balanced" array. Design an algorithm to judge whether an array is balance, with limit: Time O(N), Space O(N).
Here is an example:
a = [1,7,4,2,6,5,4,2,2,9,8];
b = [1,8,10,5,3,1,2,3]
a is balanced, 'cause the element 4, 5, 9 divide the array into [1,7], [2,6], [4,2,2], [8], the sum of each is 8.
b is not balanced, because we can not find a solution.
Any idea is appreciated!
Hints
Consider the first element to be removed.
Once you know this position, you can compute the size of the first part.
Once you know the size of the first part, you can compute the location of the second element to be removed, and so on (because all elements are positive integers).
Now you need to find a way to perform this in O(N). Try thinking about what you can do to reuse computations that have already been done, e.g. by keeping a rolling sum of the size of each of your parts.
You can try with this solution:
class BalancedArray
{
public static void main( String[] args ) throws java.lang.Exception
{
int[] a = { 1, 7, 4, 2, 6, 5, 4, 2, 2, 9, 8 }; //BALANCED
//int[] a = {7,0,6,1,0,1,1,5,0,1,2,2,2}; //BALANCED
//int[] a = {1}; //NOT BALANCED
int l = a.length;
if ( l < 7 )
{
System.out.println( "Array NOT balanced" );
} else
{
int maxX = l - 5;
int maxY = l - 3;
int maxZ = l - 1;
int x = 1;
int y = 3;
int z = 5;
int sumX = 0; //From 0 to x
int sumY = 0; //From x to y
int sumJ = 0; //From y to z
int sumZ = 0; //From z to l
for(x = 1; x < maxX; x++)
{
sumX = calcSum(a,0,x);
for(y = x + 2; y < maxY; y++)
{
sumY = calcSum(a,x+1,y);
if(sumY != sumX){
continue;
}
for(z = y + 2; z < maxZ; z++)
{
sumJ = calcSum(a,y+1,z);
if(sumJ != sumY)
{
continue;
}
sumZ = calcSum(a,z+1,l);
if(sumZ != sumJ){
continue;
}
if(sumZ == sumX && sumX == sumY && sumY == sumJ)
{
System.out.println( "Array balanced!!! Elements -> X:" + x + " Y: " + y + " Z:" + z );
return;
}
}
}
}
System.out.println("Array NOT balanced!!");
}
}
private static int calcSum(int[] src, int start, int end)
{
int toReturn = 0;
for ( int i = start; i < end; i++ )
{
toReturn += src[i];
}
return toReturn;
}
}
I made these assumptions:
between each of the three elements, which should split the array in 4 parts, there must be at least a distance of 2;
to be divided in 4 sub-arrays the source array must be at least 7 elements long;

Compile Error: not a statement

Here is the code:
public class Driver06
{
public static void main(String[] args)
{
(int) (NUMITEMS = Math.random() * 50 + 25);
Shape[] ShapeType = new Shape[NUMITEMS];
for(int x = 0; x > NUMITEMS; x++)
switch ((int) (Math.random() * 3 + 1)) //
{
case 0:
ShapeType[x] = new Circle(Math.random());
break;
case 1:
ShapeType[x] = new Rectangle(Math.random(), Math.random());
break;
case 2:
ShapeType[x] = new Triangle(Math.random());
break;
case 3:
ShapeType[x] = new Square(Math.random());
break;
}
for(int i = 0; i > ShapeType.length; i++)
{
System.out.println("" + ShapeType[x].findArea());
}
}
}
Error:
Driver06.java:10: not a statement (int) (NUMITEMS = Math.random() * 50 + 25);
(int) (NUMITEMS = Math.random() * 50 + 25);
Instead of the above (which is syntactically invalid), I believe you want:
int NUMITEMS = (int)(Math.random() * 50 + 25);
int NUMITEMS declares the variable NUMITEMS of type int
= (int)(Math.random() * 50 + 25) assigns it to the result of Math.random() * 50 + 25 cast as an integer (i.e. with its fractional part truncated).
Thanks to #pennstatephil for pointing out that your loop conditions are incorrect in the comments, they should be:
for (int x = 0; x < NUMITEMS; x++)
and
for(int i = 0; i < ShapeType.length; i++)
i.e. you want to loop as long as the loop control variable is less than the number of items / array length.
Oh, and in your second loop you probably want to refer to ShapeType[i] instead of ShapeType[x].
When you type:
for(int x = 0; x > NUMITEMS; x++){
}
This for loop starts with x = 0, each time adds +1 at x value, and this loop works while x > NUMITEMS. The loop starts from x = 0, it'll stop instantly because x is not bigger than NUMITEMS.

Adding last average value

I'm having trouble adding the last number of the loop that I have. I don't have any ideas how to include the last number and then add it to the double variable and then divide it to make the average. I would use my IDE to solve the problem but the input has to be approximately 1000 trials in order to be accurate. You can plainly see that 10 trials of 3.0 or higher does not equal approximately 2.8. I just need to have the missing trial added and then calculated into the average.
Code:
import java.util.*;
public class CalculatePI2
{
public static boolean ifitisInside (double xPosion, double yPosion)
{
double distance = Math.sqrt((xPosion * xPosion) + (yPosion * yPosion));
return (distance < 1.0);
}
public static double calculatePI (int numThrows)
{
Random randomGen = new Random();
int hits = 0;
double PI = 0;
double Alpha=0;
double average= 0;
for( int m=0; m<10; m++)
{
Alpha=+PI;
average= m/Alpha;
if(m>=0)
{
hits=0;
PI=0;
for (int i = 0; i <= numThrows; i++)
{
double xPosion = (randomGen.nextDouble()) * 2 - 1.0;
double yPosion = (randomGen.nextDouble()) * 2 - 1.0;
if (ifitisInside(xPosion, yPosion))
{
hits++;
double dthrows = numThrows;
PI =+ (4.0 * (hits/dthrows));
}
}
System.out.println("Trial["+m+"]: ="+ PI);
}
}
System.out.println("Estimate:"+average);
return PI;
}
public static void main (String[] args)
{
Scanner pie = new Scanner (System.in);
System.out.println("This program approximates PI using the Monte Carlo method. By simulating throwing darts at a dartboard. ");
System.out.print("Please enter number of throws: ");
int numThrows = pie.nextInt();
double PI = calculatePI(numThrows);
}
}
Just take the average computation out of the inner loop. Also, the loop invariant is from 0 to < numthrows, not <= numthrows. Also, your initialization of the variables needs to happen for each of your 10 trials, so it needs to be moved inside the loop.
double sumPiOverMTrials = 0;
for( int m=0; m<10; m++)
{
double hits = 0;
for (int i = 0; i < numThrows; i++) {
double xPosition = (randomGen.nextDouble()) * 2 - 1.0;
double yPosition = (randomGen.nextDouble()) * 2 - 1.0;
if (ifitisInside(xPosition, yPosition))
{
hits++;
}
}
double pi = 4.0 * hits/numthrows;
System.out.println("Trial["+m+"]: ="+ pi);
sumPiOverMTrials += pi;
}
System.out.println("Average over "+m+" trials ="+ sumPiOverMTrials/10);
I think you can solve this just by rearranging your code:
public static double calculatePI (int numThrows)
{
Random randomGen = new Random();
int hits = 0;
double PI = 0;
double Alpha=0;
double average= 0;
for( int m=0; m<10; m++)
{
for (int i = 0; i <= numThrows; i++)
{
double xPosion = (randomGen.nextDouble()) * 2 - 1.0;
double yPosion = (randomGen.nextDouble()) * 2 - 1.0;
if (ifitisInside(xPosion, yPosion))
{
hits++;
double dthrows = numThrows;
PI += (4.0 * (hits/dthrows)); // NOTE: += not =+
}
}
Alpha+=PI; // NOTE += not =+
average= m/Alpha;
if(m>=0)
{
hits=0;
PI=0;
}
System.out.println("Trial["+m+"]: ="+ PI);
}
}
This way the average is calculated after each trial rather than before. Also, I don't know much about this particular algorithm, but I think that this line:
average=m/Alpha;
should be:
average=Alpha/m

Maze not working?

code:
Array is a predefined boolean array that I made, and val is the length of the array (it is a square). I use it as a starting point, rather than using a random value
import java.util.*;
import javax.swing.*;
public class Main
{
public void main()
{
String Val = JOptionPane.showInputDialog("Enter the number of rows/columns");
int x = Integer.parseInt(Val);
boolean mazeArch[][] = new boolean [x][x];
BoundariesDeclared(mazeArch, x);
generateMaze(mazeArch, x);
convertArray(mazeArch, x);
}
public void printArray(String Array[][]) // Prints out the array
{
for (int i =0; i < Array.length; i++) {
for (int j = 0; j < Array.length; j++) {
System.out.print(" " + Array[i][j]);
}
System.out.println("");
}
}
public void convertArray(boolean Array[][], int z)
{
String RealArray[][] = new String [z][z];
for(int x = 0; x < Array.length; x++)
{
for(int y = 0; y < Array.length; y++)
{
if(Array[x][y] == true)
{
RealArray[x][y] = "*";
}
if(Array[x][y] == false)
{
RealArray[x][y] = " ";
}
}
}
printArray(RealArray);
}
public void BoundariesDeclared(boolean Array[][], int y)
{
for(int x = 0; x < Array.length; x++)
Array[0][x] = true;
for (int x = 0; x < Array.length; x++)
Array[x][0] = true;
for (int x = 0; x < Array.length; x++)
Array[x][Array.length-1] = true;
for (int x = 0; x < Array.length; x++)
Array[Array.length-1][x] = true;
}
public void generateMaze(boolean Array[][], int val)
{
Stack<Integer> StackX = new Stack<Integer>();
Stack<Integer> StackY = new Stack<Integer>();
int x = val / 2; // Start in the middle
int y = val / 2; // Start in the middle
StackX.push(x);
StackY.push(y);
while(!StackX.isEmpty())
{
Array[x][y] = true; // is Visited
x = StackX.peek();
y = StackY.peek();
if(Array[x][y+1] == false)
{
StackX.push(x);
StackY.push(y+1);
y = y + 1;
}
else if(Array[x][y-1] == false)
{
StackX.push(x);
StackY.push(y-1);
y = y - 1;
}
else if(Array[x+1][y] == false)
{
StackX.push(x+1);
StackY.push(y);
x = x+1;
}
else if(Array[x-1][y] == false)
{
StackX.push(x-1);
StackY.push(y);
x = x-1;
}
else
{
StackX.pop();
StackY.pop();
}
}
}
}
Whenever I print the results, I only get stars, which mean that every single boolean is set to true. I understand my error, because I am visiting every spot the result will be that they are all set to true. But what can i do to fix this? I think I have the concept correct, just not the application. I previously asked the question and was told that I need to make two Arrays (1 for walls, another for visiting) but how would I apply this as well?
You didn't mention what are you trying to do. So not much we can help.
What is this maze doing?
What's your input?
What's your expected result?
Add this line and debug yourself.
public void generateMaze(boolean Array[][], int val) {
Stack<Integer> StackX = new Stack<Integer>();
Stack<Integer> StackY = new Stack<Integer>();
int x = val / 2; // Start in the middle
int y = val / 2; // Start in the middle
StackX.push(x);
StackY.push(y);
while (!StackX.isEmpty()) {
Array[x][y] = true; // is Visited
x = StackX.peek();
y = StackY.peek();
if (Array[x][y + 1] == false) {
StackX.push(x);
StackY.push(y + 1);
y = y + 1;
} else if (Array[x][y - 1] == false) {
StackX.push(x);
StackY.push(y - 1);
y = y - 1;
} else if (Array[x + 1][y] == false) {
StackX.push(x + 1);
StackY.push(y);
x = x + 1;
} else if (Array[x - 1][y] == false) {
StackX.push(x - 1);
StackY.push(y);
x = x - 1;
} else {
StackX.pop();
StackY.pop();
}
convertArray(Array, val); // add this line
}
}
The solution is still the same as when you last posted this question - you need to have two arrays
-one that is true for every place in the maze that is a wall - the maze's tiles
-one that starts all false - the solver's tiles
The solver can move onto a tile only if both arrays are false at that point, and sets the second array (the solver's tiles) to true while leaving the first array (the maze's tiles) alone.
This is not a 'coding' bug, per say. You simply don't know what behavior you want. Try commenting out the line where you generate the maze. Run your program with 6 as a parameter. You get:
* * * * * *
* *
* *
* *
* *
* * * * * *
What kind of maze is this? Where is the exit? Again, this is not a coding issue, this is a design flaw. Of course if you start within the bounds of this maze, you will visit all of the squares!
I'm not clear what do you expect in your output exactly, but I can see where the issue is. In your generateMaze() method you are travelling like in spiral mode which ends up touching each and every node in the end. Like suppose you have 5x5 array, you travel and make true like (boundaries are already true) [2,2]->[2,3]->[3,3]->[3,2]->[3,1]->[2,1]->[1,1]->[1,2]->[1,3]
you start from middle, you start visiting and take turns just before you find already true (boundary or visited), and it covers all the nodes

Categories