Polynomial Class in Java problems - java

I'm having trouble with this polynomial class, specifically the checkZero and differentiate methods. The checkZero class is supposed to see if there are any leading coefficients in the polynomial, and if so, it should resize the coefficient array. The differentiate method should find the derivative of a polynomial, but I keep getting ArrayIndexOutOfBounds errors.
public class Polynomial {
private float[] coefficients;
public static void main (String[] args){
float[] fa = {3, 2, 4};
Polynomial test = new Polynomial(fa);
}
public Polynomial() {
coefficients = new float[1];
coefficients[0] = 0;
}
public Polynomial(int degree) {
coefficients = new float[degree+1];
for (int i = 0; i <= degree; i++)
coefficients[i] = 0;
}
public Polynomial(float[] a) {
coefficients = new float[a.length];
for (int i = 0; i < a.length; i++)
coefficients[i] = a[i];
}
public int getDegree() {
return coefficients.length-1;
}
public float getCoefficient(int i) {
return coefficients[i];
}
public void setCoefficient(int i, float value) {
coefficients[i] = value;
}
public Polynomial add(Polynomial p) {
int n = getDegree();
int m = p.getDegree();
Polynomial result = new Polynomial(Polynomial.max(n, m));
int i;
for (i = 0; i <= Polynomial.min(n, m); i++)
result.setCoefficient(i, coefficients[i] + p.getCoefficient(i));
if (i <= n) {
//we have to copy the remaining coefficients from this object
for ( ; i <= n; i++)
result.setCoefficient(i, coefficients[i]);
} else {
// we have to copy the remaining coefficients from p
for ( ; i <= m; i++)
result.setCoefficient(i, p.getCoefficient(i));
}
return result;
}
public void displayPolynomial () {
for (int i=0; i < coefficients.length; i++)
System.out.print(" "+coefficients[i]);
System.out.println();
}
private static int max (int n, int m) {
if (n > m)
return n;
return m;
}
private static int min (int n, int m) {
if (n > m)
return m;
return n;
}
public Polynomial multiplyCon (double c){
int n = getDegree();
Polynomial results = new Polynomial(n);
for (int i =0; i <= n; i++){ // can work when multiplying only 1 coefficient
results.setCoefficient(i, (float)(coefficients[i] * c)); // errors ArrayIndexOutOfBounds for setCoefficient
}
return results;
}
public Polynomial multiplyPoly (Polynomial p){
int n = getDegree();
int m = p.getDegree();
Polynomial result = null;
for (int i = 0; i <= n; i++){
Polynomial tmpResult = p.multiByConstantWithDegree(coefficients[i], i); //Calls new method
if (result == null){
result = tmpResult;
} else {
result = result.add(tmpResult);
}
}
return result;
}
public void checkZero(){
int newDegree = getDegree();
int length = coefficients.length;
float testArray[] = coefficients;
for (int i = coefficients.length-1; i>0; i--){
if (coefficients[i] != 0){
testArray[i] = coefficients[i];
}
}
for (int j = 0; j < testArray.length; j++){
coefficients[j] = testArray[j];
}
}
public Polynomial differentiate(){
int n = getDegree();
int newPolyDegree = n - 1;
Polynomial newResult = new Polynomial();
if (n == 0){
newResult.setCoefficient(0, 0);
}
for (int i =0; i<= n; i++){
newResult.setCoefficient(i, coefficients[i+1] * (i+1));
}
return newResult;
}
}

There might be more problems, but one is a problem with your differentiate method:
int n = getDegree();
...
Polynomial newResult = new Polynomial();
...
for (int i = 0; i <= n; i++)
{
newResult.setCoefficient(i, coefficients[i + 1] * (i + 1)); //This line
}
Your paramaterless constructor initializes an array with length 1, so "newResult" will only have 1 index, and you try to put something into place i, which goes above 1 if the Polynomial you are in have an array of greater length than 1.

First, a few code notes:
New arrays are automatically initialized to 0 in Java. This is not needed.
coefficients = new float[degree+1];
for (int i = 0; i <= degree; i++)
coefficients[i] = 0;
I also see many lines which might become more readable and compact if you use the trinary operator, for example:
int i;
for (i = 0; i <= Polynomial.min(n, m); i++)
result.setCoefficient(i, coefficients[i] + p.getCoefficient(i));
if (i <= n) {
//we have to copy the remaining coefficients from this object
for ( ; i <= n; i++)
result.setCoefficient(i, coefficients[i]);
} else {
// we have to copy the remaining coefficients from p
for ( ; i <= m; i++)
result.setCoefficient(i, p.getCoefficient(i));
}
Could become something like
for (int i = 0; i <= result.getDegree(); i++)
result.setCoefficient(i,
i>n?0:coefficients[i] +
i>m?0:p.getCoefficient(i));
The one bug I did spot was here:
int n = getDegree();
....
for (int i =0; i<= n; i++){
newResult.setCoefficient(i, coefficients[i+1] * (i+1));
}
This will always call coefficients[coefficients.length] on the last iteration, which will always fail.
The stack trace of the exception when you ran this program should tell you exactly where the error is, by the way.

Related

java.lang.StackOverflowError on factorial function being called by another recursive function

I have a factorial function on my program that works fine until i try to execute the function deleteRepeated(), the console is telling me that the error is in the return of the factorial function, maybe it's being called by a single function too many times in a short period of time? I've been stuck for hours.
import java.util.Scanner;
public class ex9 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int[] newArr = new int[n - repeated(arr)];
int[] finalArr = deleteRepeated(arr, newArr);
for (int a : finalArr) {
System.out.println(a);
}
}
public static long factorial(int n) {
if (n == 0)
return 1;
return (n * factorial(n - 1));
}
public static int repeated(int arr[]) {
int n = arr.length;
int mix = (int) (factorial(n) / (2 * factorial(n - 2)));
int i = 0;
int k = 0;
int rep = 0;
int a = -100;
while (i < mix) {
for (int j = k + 1; j < n; j++) {
if (arr[k] == arr[j] && a != j) {
a = j;
rep += 1;
}
i++;
}
k++;
}
return rep;
}
public static int[] deleteRepeated(int arr[], int newArr[]) {
int n = arr.length;
int rep = repeated(arr);
int i = 0;
int k = 0;
int a = -100;
while (i < newArr.length) {
for (int j = k + 1; j < n; j++) {
if (arr[k] == arr[j] && a != arr[k]) {
a = arr[j];
newArr[k] = arr[k];
}
i++;
}
k++;
}
rep = repeated(newArr);
if (rep > 0) {
int[] newArr2 = new int[newArr.length - rep];
deleteRepeated(newArr, newArr2);
}
return newArr;
}
}
Only thing i could do to avoid the error was stopping the function from executing :/, maybe it has to do with how i'm re-calling it at the end of each execution...? is what i did allowed?
So, deleteRepeated is all messed up. The issue is deleteRepeated does not actually remove duplicate elements, so the check for the base case of recursion always fails. I'm not sure why you're using recursion here anyway; if the while loop worked properly, it could remove all duplicates without need for recursion.
It appears that you copy-pasted the implementation of repeated into deleteRepeated, and you replaced the logic for handling repeated elements with logic that handles non-repeated elements.
Here is how I would implement the method:
public static int deleteRepeated(int arr[], int newArr[]) {
int n = 0;
for(int i = 0; i < arr.length; i++) {
boolean unique = true;
for(int j = 0; j < n; j++)
unique = unique && newArr[j] != arr[i];
if(unique)
newArr[n++] = arr[i];
if(n >= newArr.length) break;
}
return n;
}

memoized matrix chain multiplication in Java

I feel like I'm really close with this implementation of a memoized matrix chain algorithm in Java, but I'm getting an array out of bounds error on line 45 and 53. These, for some reason, really seem to mess me up. Maybe there's something I'm continually messing up with, but I dunno, obviously. Can anyone help me out?
public class Lab2 {
//fields
static int p[];
static int m[][];
final static int INFINITY = 999999999;
public Lab2() {
//
}
public static void main(String[] args) {
Lab2 lab2 = new Lab2();
Lab2.m = new int[7][7];
Lab2.p = new int[7];
Lab2.p[0] = 20;
Lab2.p[1] = 8;
Lab2.p[2] = 4;
Lab2.p[3] = 25;
Lab2.p[4] = 30;
Lab2.p[5] = 5;
Lab2.p[6] = 10;
int n = Lab2.p.length-1;
//initialize m array to infinity
for (int i = 1; i <= n; i++){
for (int j = i; j <= n; j++){
Lab2.m[i][j]= INFINITY;
}
}
lab2.lookUpChain(m, p, 1, n);
for (int i = 0; i < 8; i++){
for (int j = 0; j < 8; j++){
System.out.println(m[i][j]);
}
}
}
//
public int lookUpChain(int m[][], int p[], int i, int j ){
if (m[i][j]<INFINITY){
return m[i][j];
}
if (i == j){
m[i][j] = 0;
}
else{
for (int k = i; k <= j; i++){
int q = (lookUpChain(m,p,i,k)) + (lookUpChain(m,p,k+1,j)) + (p[i]*p[k]*p[j]);
if (q < m[i][j]){
m[i][j] = q;
}
}
}
return m[i][j];
}
}
else{
for (int k = i; k <= j; i++)
Change to:
else{
for (int k = i; k <= j; k++) // change i to k

Polynomial class Java

I'm trying to make two methods for a Polynomial class but I'm having troubles.
The first method checkZeros is supposed to check if there are any leading zeros in the coefficients of a polynomial. The method should resize the coefficient array if there are leading zeros. The second method should find the derivative of a polynomial, but I keep getting ArrayIndexOutOfBounds errors.
Here they are:
public class Poly {
private float[] coefficients;
public static void main (String[] args){
float[] fa = {3, 2, 4};
Poly test = new Poly(fa);
}
public Poly() {
coefficients = new float[1];
coefficients[0] = 0;
}
public Poly(int degree) {
coefficients = new float[degree+1];
for (int i = 0; i <= degree; i++)
coefficients[i] = 0;
}
public Poly(float[] a) {
coefficients = new float[a.length];
for (int i = 0; i < a.length; i++)
coefficients[i] = a[i];
}
public int getDegree() {
return coefficients.length-1;
}
public float getCoefficient(int i) {
return coefficients[i];
}
public void setCoefficient(int i, float value) {
coefficients[i] = value;
}
public Poly add(Poly p) {
int n = getDegree();
int m = p.getDegree();
Poly result = new Poly(Poly.max(n, m));
int i;
for (i = 0; i <= Poly.min(n, m); i++)
result.setCoefficient(i, coefficients[i] + p.getCoefficient(i));
if (i <= n) {
//we have to copy the remaining coefficients from this object
for ( ; i <= n; i++)
result.setCoefficient(i, coefficients[i]);
} else {
// we have to copy the remaining coefficients from p
for ( ; i <= m; i++)
result.setCoefficient(i, p.getCoefficient(i));
}
return result;
}
public void displayPoly () {
for (int i=0; i < coefficients.length; i++)
System.out.print(" "+coefficients[i]);
System.out.println();
}
private static int max (int n, int m) {
if (n > m)
return n;
return m;
}
private static int min (int n, int m) {
if (n > m)
return m;
return n;
}
public void checkForZeros(){
int newDegree = getDegree();
int length = coefficients.length;
double testArray[] = coefficients;
for (int i = length - 1; i >0; i--) {
if (coefficients[i] != 0) {
testArray[i] = coefficients[i];
}
}
for (int j = 0; j < testArray.length; j++){
coefficients[j] = testArray[j];
}
}
public Poly differentiate(){
int n = getDegree();
int newPolyDegree = n - 1;
Poly newResult = new Poly();
if (n == 0){
newResult.setCoefficient(0, 0);
}
for (int i =0; i<= n; i++){
newResult.setCoefficient(i, coefficients[i+1] * (i+1));
}
return newResult;
}
}
I would suspect the problem is here
for (int i =0; i<= n; i++){
newResult.setCoefficient(i, coefficients[i+1] * (i+1));
}
Since n = getDegree();, let's assume the polynomial is of 1st degree (1+x for example). Then n=1 I would guess, and coefficients has a length of 2. But you are going to be checking coefficients[2] (since you have i+1) which is out of bounds. I'm guessing you want
for (i=0; i<=newPolyDegree; i++){
newResult.setCoefficient(i, coefficients[i] * (i+1));
}
or something... It's hard to tell with the amount of code you gave.
You are most probably getting ArrayIndexOutofBounds because you've implemented checkzeroes in a wrong manner and hence getdegree() is returning a size less than the coefficient array. Consider the following polynomial:
f(x) = 2x^3 + 5x + 1
The coefficient array will be
[2,0,5,1]
After checkzeroes, it becomes
[2,5,1] (because you're removing all zeroes, not just leading zeroes.)
I suppose the degree function will still return 3 and you'll run out of array bounds in differentiate()
The error is in the loop.
for (int i =0; i<= n; i++){
newResult.setCoefficient(i, coefficients[i+1] * (i+1));
Base on little information, I assume:
1. setCoefficient(power of x, coefficient of x)
So in this case, we have a polynomial of degree n for differentiation, which have n+1 term, starting from 0->n (x^0 -> x^n)
Look at the loop, when i=n, it have to fetch the coefficient of x^(n+1) which is not exist.
You should do.
for (int i =0; i< n; i++){
newResult.setCoefficient(i, coefficients[i+1] * (i+1));

Multiplying polynomial by constant in Java

I'm having some problems with multiplying a Polynomial by a constant (double). It works when theres only one coefficient but when more then one is there, it gives a ArrayIndexOutOfBounds error and points to the setCoefficient method. Any help? Thanks
public class Poly {
private float[] coefficients;
public Poly() {
coefficients = new float[1];
coefficients[0] = 0;
}
public Poly(int degree) {
coefficients = new float[degree+1];
for (int i = 0; i <= degree; i++)
coefficients[i] = 0;
}
public Poly(float[] a) {
coefficients = new float[a.length];
for (int i = 0; i < a.length; i++)
coefficients[i] = a[i];
}
public int getDegree() {
return coefficients.length-1;
}
public float getCoefficient(int i) {
return coefficients[i];
}
public void setCoefficient(int i, float value) {
coefficients[i] = value;
}
public Poly add(Poly p) {
int n = getDegree();
int m = p.getDegree();
Poly result = new Poly(Poly.max(n, m));
int i;
for (i = 0; i <= Poly.min(n, m); i++)
result.setCoefficient(i, coefficients[i] + p.getCoefficient(i));
if (i <= n) {
//we have to copy the remaining coefficients from this object
for ( ; i <= n; i++)
result.setCoefficient(i, coefficients[i]);
} else {
// we have to copy the remaining coefficients from p
for ( ; i <= m; i++)
result.setCoefficient(i, p.getCoefficient(i));
}
return result;
}
public void displayPoly () {
for (int i=0; i < coefficients.length; i++)
System.out.print(" "+coefficients[i]);
System.out.println();
}
private static int max (int n, int m) {
if (n > m)
return n;
return m;
}
private static int min (int n, int m) {
if (n > m)
return m;
return n;
}
public Poly multiplyCon (double c){
int n = getDegree();
Poly results = new Poly();
// can work when multiplying only 1 coefficient
for (int i =0; i <= coefficients.length-1; i++){
// errors ArrayIndexOutOfBounds for setCoefficient
results.setCoefficient(i, (float)(coefficients[i] * c));
}
return results;
}
}
Replace Poly results = new Poly(); with Poly results = new Poly(n);.
I believe you should replace in multiplyCon method
Poly results = new Poly();
with
Poly results = new Poly(n);
Poly default constructor creates array with only one coefficient, which explains why multiplying a one-coefficient Polynomial works.

Java permutations

I am trying to run my code so it prints cyclic permutations, though I can only get it to do the first one at the moment. It runs correctly up to the point which I have marked but I can't see what is going wrong. I think it has no break in the while loop, but I'm not sure. Really could do with some help here.
package permutation;
public class Permutation {
static int DEFAULT = 100;
public static void main(String[] args) {
int n = DEFAULT;
if (args.length > 0)
n = Integer.parseInt(args[0]);
int[] OA = new int[n];
for (int i = 0; i < n; i++)
OA[i] = i + 1;
System.out.println("The original array is:");
for (int i = 0; i < OA.length; i++)
System.out.print(OA[i] + " ");
System.out.println();
System.out.println("A permutation of the original array is:");
OA = generateRandomPermutation(n);
printArray(OA);
printPemutation(OA);
}
static int[] generateRandomPermutation(int n)// (a)
{
int[] A = new int[n];
for (int i = 0; i < n; i++)
A[i] = i + 1;
for (int i = 0; i < n; i++) {
int r = (int) (Math.random() * (n));
int swap = A[r];
A[r] = A[i];
A[i] = swap;
}
return A;
}
static void printArray(int A[]) {
for (int i = 0; i < A.length; i++)
System.out.print(A[i] + " ");
System.out.println();
}
static void printPemutation(int p[])// (b)
{
System.out
.println("The permutation is represented by the cyclic notation:");
int[] B = new int[p.length];
int m = 0;
while (m < p.length)// this is the point at which my code screws up
{
if (!check(B, m)) {
B = parenthesis(p, m);
printParenthesis(B);
m++;
} else
m++;
}// if not there are then repeat
}
static int[] parenthesis(int p[], int i) {
int[] B = new int[p.length];
for (int a = p[i], j = 0; a != B[0]; a = p[a - 1], j++) {
B[j] = a;
}
return B;
}
static void printParenthesis(int B[]) {
System.out.print("( ");
for (int i = 0; i < B.length && B[i] != 0; i++)
System.out.print(B[i] + " ");
System.out.print(")");
}
static boolean check(int B[], int m) {
int i = 0;
boolean a = false;
while (i < B.length || !a) {
if ((ispresent(m, B, i))){
a = true;
break;
}
else
i++;
}
return a;
}
static boolean ispresent(int m, int B[], int i) {
return m == B[i] && m < B.length;
}
}
Among others you should check p[m] in check(B, p[m]) instead of m:
in static void printPemutation(int p[]):
while (m < p.length){
if (!check(B, p[m])) {
B = parenthesis(p, m);
printParenthesis(B);
}
m++;
}
then
static boolean check(int B[], int m) {
int i = 0;
while (i < B.length) {
if (m == B[i]) {
return true;
}
i++;
}
return false;
}
this does somehow more what you want, but not always i fear...

Categories

Resources