Adding duplicates in an ArrayList - java

I am stuck on how to find duplicate entries in an ArrayList and then manipulate them. I am implementing a polynomial class and I want to add monomials of the same order to create a new polynomial. Monomials have a degree and a coefficient. I want to cycle through a collection of monomials and find the monomials that have the same power and add the coefficients. The sum of all these like powered monomials will be the polynomial.

ArrayList (or any List) accepts duplicates.
However, since you want to group Monomials by their power, you might consider using a Map<Integer,Foo> where the key is the power. Foo has a lot of options. Foo could be an ArrayList<Monomial>, an ArrayList<Double>, holding only the coefficiants, that you add later. This requires some code writing on your part or else using a 3rd partly library for a MultiMap.
Or, Foo could be a Double which represents the summed coefficient, in which case you need to write an add(Monomial) method which updates the Double everytime.
If the possible range of powers is small and known, you could use a simple array too.

Here's my solution, you can add two polynomials of the same degree. Watch for bugs.
public class Polynome {
private double[] coefficients;
private int degre;
public Polynome(int degre) {
if (degre < 0) {
System.out.println("Invalid Degree");
}
this.degre = degre;
coefficients = new double[degre + 1];
for (int i = 0; i < degre; i++)
coefficients[i] = 0;
coefficients[degre] = 1;
}
public void setCoefficient(int degre, double coefficient) {
if (degre < 0 || degre > this.degre) {
System.out.println("Invalid Degree");
}
if (coefficient == 0 && degre == this.degre && this.degre != 0) {
System.out.println("Null Degree");
}
coefficients[degre] = coefficient;
}
/*
* Returns the coeff giving the degree of the element
*/
public double getCoefficient(int degre) {
if (degre < 0 || degre > this.degre) {
return 0;
}
if (degre == this.degre && this.degre != 0) {
return coefficients[this.getDegre()];
}
return this.coefficients[degre];
}
public String ToString() {
if (degre == 0)
return "" + this.coefficients[0];
String result = "" + this.coefficients[degre]+" x^" + degre;
for (int i = degre-1 ; i > 0 ; i--){
if (this.coefficients[i] < 0) {
result += "-" + Math.abs(this.coefficients[i]) + " x^" + i;
}
else {
if (this.coefficients[i] > 0){
result += " + " + this.coefficients[i] + " x^" + i;
}
}
}
if (this.coefficients[0]!= 0) result += " + " + this.coefficients[0] ;
return result;
}
/*
* Returns the degree of the current poly
*/
public int getDegre() {
return degre;
}
/*
* Adds two Polys with the same degrees
*/
public Polynome add(Polynome p) {
Polynome result = new Polynome(p.getDegre());
int deg = result.getDegre();
for(int i = deg ; i >0 ; i--) {
result.coefficients[i] = this.getCoefficient(i) + p.getCoefficient(i);
}
return result;
}
public static void main(String...args) {
Polynome p = new Polynome(2);
p.setCoefficient(2, 7);
Polynome p1 = new Polynome(2);
p1.setCoefficient(2, 2);
System.out.println(p.ToString() + "\n" + p1.ToString() + "\n\n" + (p.add(p1)).ToString());
}
}

Related

What is alpha sampling parameter in Cybozu for language detection?

****I checked below code in Cybozu for alpha parameter and how they have used it. It Looks like will reduce the weight if you are reducing alpha **
private boolean updateLangProb(double[] prob, String word, double alpha) {
if (word != null && this.wordLangProbMap.containsKey(word)) {
double[] langProbMap = (double[])this.wordLangProbMap.get(word);
if (this.verbose) {
System.out.println(word + "(" + unicodeEncode(word) + "):" + this.wordProbToString(langProbMap));
}
double weight = alpha / 10000.0D;
for(int i = 0; i < prob.length; ++i) {
prob[i] *= weight + langProbMap[i];
}
return true;
} else {
return false;
}
}

Printing a polynomial

I am trying to print a polynomial from a given number.
I did the example below, but for something like 100 it will print 1x^2+, when I want just x^2. What I'm looking for is how can I make it to not print + and at the same time get rid of coefficients that are 1.
Edit: I did it, it prints perfectly. Feel free to use it.
private static String S_frumos(int poli) {
String s = "";
for (int i = 0; i < String.valueOf(poli).length(); i++) {
int nr = Character.getNumericValue(S_GetCoefs(poli, i));
if (nr != 0) {
if (i == String.valueOf(poli).length() - 1) {
s = s + nr;
} else if (i == String.valueOf(poli).length() - 2) {
if ((S_zero(poli, i + 1) == 1)) {
if (nr != 1) {
s = s + nr + "x";
} else {
s = s + "x";
}
} else {
if (nr != 1) {
s = s + nr + "x" + "+";
} else {
s = s + "x" + "+";
}
}
} else if ((S_zero(poli, i + 1) == 1)) {
if (nr != 1) { s = s + nr + "x^" + (String.valueOf(poli).length() - i - 1);}
else { s = s + "x^" + (String.valueOf(poli).length() - i - 1);}
} else {
if (nr != 1){ s = s + nr + "x^" + (String.valueOf(poli).length() - i - 1) + "+";}
else { s = s + "x^" + (String.valueOf(poli).length() - i - 1) + "+";}
}
}
}
return s;
}
private static int S_GetCoefs(int poli, int x) {
return String.valueOf(java.lang.Math.abs(poli)).charAt(x);
}
To store something of an unknown length... then you can still use an int/double array, just gets slightly more complicated.
public static void main(String[] args)
{
// Say the size is given in a command line argument.
int coefficientNumber = Integer.parseInt(args[0]);
int[] poly = new int[coefficientNumber];
for (int i = 0; i < poly.length; i++)
{
poly[i] = 0;
}
// Set the highest coeffient to 1 (if there is 3 coefficients, this is coefficient
// of x^2, if 4 coefficients, this is coefficient of x^3
poly[0] = 1;
printPoly(poly);
}
// To print a polynomial of unknown length.
// If the coefficient is 0, don't print it.
private static void printPoly(int[] poly)
{
String output = "";
for (int index = 0; index < poly.length; index++)
{
if (poly[index] != 0)
{
// If this is the first coefficient with a value
if (output.length() == 0)
output = poly[index] + "x^" + (poly.length - (index + 1));
// Else if there is already some coefficient with values printed.
else
output += " + " + "x^" + (poly.length - (index + 1));
} // if
} // for
System.out.println(output);
} // printPoly
First of all, storing a polynomial in one variable isn't a great idea as if you have coefficients of more than 9 you'll get confused.
A better method imo (without making a polynomial class) is to store the polynomial in an int/double array.
public static void main(String[] args)
{
// To store the polynomial x^2, you could do the following:
int[] poly = new int[3];
poly[0] = 1;
poly[1] = 0;
poly[2] = 0;
printPoly(poly);
}
// To print it:
private static void printPoly(int[] poly)
{
String output = "";
if (poly[0] != 0)
output += poly[0] + "x^2"
if (poly[1] != 0)
{
if (output.size() > 0)
output += " + " + poly[1] + "^x";
else
output += poly[1] + "x";
}
if (poly[2] != 0)
{
if (output.size() > 0)
output += " + " + poly[2];
else
output += poly[2];
}
}

need quick help in Java Program Lab

i have a lab for my java class. I have everything except cannot get the average method to work properly. Whenever i run the program, the average is calculated from the random values and not the one updated.
package ArrayKeyAccess;
/**
* Class Definition for Data Element
* Minimal Definition -- No Error Checking
* Instructional Model -- Conceptual Emphasis
*/
public class Data
{
private int studentID;
private int test1;
private int test2;
private int test3;
private int average;
private String letterGrade;
private static int nextSID = 99; //cheap sequence number approach
private static int getNextSID()
{
return ++nextSID;
}//getNextKey
public Data(int n) //no error checking
{
this.setStudentID(getNextSID());
this.setTest1(n);
this.setTest2(n);
this.setTest3(n);
}//Data constructor
public Data(int k, int n) //no uniqueness checking
{
this.setStudentID(k);
this.setTest1(n);
this.setTest2(n);
this.setTest3(n);
}//Data constructor
public Data( Data d ) //Copy Constructor
{ //required for Composition
this.setStudentID(d.getStudentID());
this.setTest1(d.getTest1());
this.setTest2(d.getTest2());
this.setTest3(d.getTest3());
this.calculateAverage(getTest1(), getTest2(), getTest3());
this.determineLetterGrade(letterGrade);
}//copy constructor
public Data copy() //Copy Object
{ //required for Compostion
return new Data(this);
}//copy object
public String toString()
{
return "Student ID: " + this.getStudentID() + '\n' +
"Test 1: " + this.getTest1() + '\n' +
"Test 2: " + this.getTest2() + '\n' +
"Test 3: " + this.getTest3() + '\n' +
"Average: " + this.getAverage() + '\n' +
"Letter Grade: " + this.getLetterGrade() + '\n';
}//toString
public void setStudentID (int n) //no error checking
{
studentID = n;
}
public int getStudentID()
{
return studentID;
}
//----------------------Test1---------------------------------------
public void setTest1(int n) //no validity checking
{
test1 = n;
}
public int getTest1()
{
return test1;
}
//----------------------Test2---------------------------------------
public void setTest2(int n) //no validity checking
{
test2 = n;
}
public int getTest2()
{
return test2;
}
//----------------------Test3---------------------------------------
public void setTest3(int n) //no validity checking
{
test3 = n;
}
public int getTest3()
{
return test3;
}
//---------------calculate average score-----------------------------
public void calculateAverage(int test1, int test2, int test3) //set
{
this.test1 = getTest1();
average = (getTest1() + getTest1() + getTest3()) / 3;
}
//----------------determine letter grade------------------------------
public void determineLetterGrade(String letterGrade)
{
if(average >= 90)
letterGrade = "A";
else if(average >= 80)
letterGrade = "B";
else if(average >= 70)
letterGrade = "C";
else if(average >= 60)
letterGrade = "D";
else
letterGrade = "F";
this.letterGrade = letterGrade;
}
//getAverageScore
public int getAverage() //get
{
return average;
}
//getLetterGrade
public String getLetterGrade()
{
return letterGrade;
}
}//class Data
ProgramTest
UnsortedArray s = new UnsortedArray(10);
int score;
//add 10 data elements
for( int i=1; i<=10; i++ )
{
score = 50 + (int)(Math.random()*50)+1;
s.insert( new Data(score) );
}
System.out.println("------------------TEST 1----------------------");
//update test 1
s.updateTest1(100,44);
s.updateTest1(101,89);
s.updateTest1(102,80);
s.updateTest1(103,95);
s.updateTest1(104,65);
s.updateTest1(105,74);
s.updateTest1(106,69);
s.updateTest1(107,56);
s.updateTest1(108,88);
s.updateTest1(109,99);
s.showList();
The Unsorted Array Class ( i forgot to attach before)
package ArrayKeyAccess;
/**
* Class Definition for Unsorted Array
* Minimal Basic Methods
* Implements Insert, Fetch, Update, Delete
* Conceptual Instructional Model
*/
public class UnsortedArray
{
private int next; //next insert position
private int size; //array capacity
private Data[] a; //reference for container of
//data elements
public UnsortedArray(int n) //no error checking
{
next = 0;
size = n;
a = new Data[size];
}//constructor
public boolean insert( Data newNode )
{
if( next >= size ) //array is full
return false;
//insert copy in next position
a[next] = new Data( newNode );
++next;
return true;
}//insert
public Data fetch( int targetKey )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return null;
else //node was found
return a[i].copy(); //return a copy
}//fetch
//Update data element field in the container
public boolean updateTest1( int targetKey, int val )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return false;
else //node was found
{
a[i].setTest1( val );
return true;
}
}//updateTest1
public boolean updateTest2( int targetKey, int val )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return false;
else //node was found
{
a[i].setTest2( val );
return true;
}
}//updateTest2
public boolean updateTest3( int targetKey, int val )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return false;
else //node was found
{
a[i].setTest3( val );
return true;
}
}//updateTest1
//overload update method
//assumes record was fetched and
//value was modified and now is
//to be "reinserted".
public boolean update( int targetKey, Data updNode )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return false;
else //node was found
{
a[i] = updNode.copy(); //assign copy
return true; //preserve Composition
}
}//update
public boolean delete( int targetKey )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return false;
else //node was found
{
a[i] = a[next-1]; //move last node to deleted position
//"deleted" node has no reference
a[next-1] = null; //new next available position
--next; //reset insert position
return true;
}
}//delete
public void showList() //List the nodes
{
for(int i=0; i<next; i++)
System.out.println( a[i] );
}//showList
}//class UnsortedArray
Well, there's two problems.
First, you're adding getTest1() twice. That's worth fixing in its own right.
The second problem is that you're going to run into integer division - simply because all four of your values are going to be ints, you won't get any floating-point values (or a "true" average).
What you want to do is change the type of average to double, then change your divdend into a floating point number, as such:
average = (getTest1() + getTest2() + getTest3()) / 3.0;
It may be because you add test1 twice.
average = (getTest1() + getTest1() + getTest3()) / 3;
i figured it out, these are my changes, no getters for calculateAverage or letterGrade
public int calculateAverage() //set
{
average = (this.getTest1() + this.getTest2() + this.getTest3()) / 3;
return average;
}
public String letterGrade()
{
if(this.average >= 90)
letterGrade = "A";
else if(this.average >= 80)
letterGrade = "B";
else if(this.average >= 70)
letterGrade = "C";
else if(this.average >= 60)
letterGrade = "D";
else
letterGrade = "F";
return letterGrade;
}
public String toString()
{
return "Student ID: " + this.getStudentID() + '\n' +
"Test 1: " + this.getTest1() + '\n' +
"Test 2: " + this.getTest2() + '\n' +
"Test 3: " + this.getTest3() + '\n' +
"Average: " + calculateAverage() + '\n' +
"Letter Grade: " + this.letterGrade() + '\n';
}//toString

How to find Largest Prime Number, Smallest Factor except 1, Sum of Numbers

Herro, Um I'm not sure if this is how you use this site but uh lets get to it... So I need help on this project and I have to do this -
Input [][] Output
A - F -> Multiply by 3, Divide by 4
G - J -> Divide by 3 + 25
K - N -> Find Greatest Factor * 2
O - Q -> Find largest prime inclusive * 3
R - W -> Find Smallest Factor Except 1
X - Z -> Sum Numbers
So I was wondering if my first couple is correct, and need help on the empty space. So the Letter represents the number of the as in "Z" is the last letter so its 26, and "A" is the first so its 1. So if an responses... Thanks ! package Fun;
import java.util.Scanner;
public class Fun {
public static void main(String[] args) {
// TODO Auto-generated method stub
run();
}
public static void run()
{
input();
evaluateAlphabet();
evaluate();
}
public static void input()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Letter, please");
x = sc.next();
}
public static String x = " ";
public static int temp = 0;
public static int answer = 0;
public static void evaluateAlphabet()
{
if(x.equals("A"))
{
temp = 1;
}
else if (x.equals("B"))
{
temp = 2;
}
else if (x.equals("C"))
{
temp = 3;
}
else if (x.equals("D"))
{
temp = 4;
}
else if (x.equals("E"))
{
temp = 5;
}
else if (x.equals("F"))
{
temp = 6;
}
else if (x.equals("G"))
{
temp = 7;
}
else if (x.equals("H"))
{
temp = 8;
}
else if (x.equals("I"))
{
temp = 9;
}
else if (x.equals("J"))
{
temp = 10;
}
else if (x.equals("K"))
{
temp = 11;
}
else if (x.equals("L"))
{
temp = 12;
}
else if (x.equals("M"))
{
temp = 13;
}
else if (x.equals("N"))
{
temp = 14;
}
else if (x.equals("O"))
{
temp = 15;
}
else if (x.equals("P"))
{
temp = 16;
}
else if (x.equals("Q"))
{
temp = 17;
}
else if (x.equals("R"))
{
temp = 18;
}
else if (x.equals("S"))
{
temp = 19;
}
else if (x.equals("T"))
{
temp = 20;
}
else if (x.equals("U"))
{
temp = 21;
}
else if (x.equals("V"))
{
temp = 22;
}
else if (x.equals("W"))
{
temp = 23;
}
else if (x.equals("X"))
{
temp = 24;
}
else if (x.equals("Y"))
{
temp = 25;
}
else if (x.equals("Z"))
{
temp = 26;
}
else if (x.equals("Qwerty"))
{
temp = 27;
}
}
public static void evaluate()
{
if(temp>=1 && temp<= 6)
{
answer = (temp * 3)/4;
System.out.println("Answer is " + answer);
}
else if(temp >= 7 && temp<= 10)
{
answer = (temp/3) + 25;
System.out.println("Answer is " + answer);
}
else if(temp >= 11 && temp<= 14)
{
}
else if(temp>=15 && temp<= 17)
{
for(int i = temp; i>0; i--)
{
for(int j = 2; j <=i/2 + 1; j++)
{
if(i%j==0)
{
break;
}
if(j==i/2 + 1)
{
answer = i * 3;
}
}
}
System.out.println("Answer is " + answer);
}
else if(temp>=18 && temp<= 23)
{
answer = temp;
}
else if(temp>= 24 && temp<=26)
answer = (answer * 12)%26;
System.out.println("Answer is " + answer);
}
}
-Corruption
Here is a better approach for char to int conversion:
Assuming the string has at least 1 character(check for its length), you can get the temp by doing:
temp = x.getCharAt(0) - 'A' + 1;
or, safety first:
temp = 0;
if (x.matches("^[A-Z]{1}$") {
temp = x.getCharAt(0) - 'A' + 1;
}
What's happening here? Every character has an ASCII code, an integer. So, when you have 2 chars and you try to get the distance between them, the result is an int. 'A' - 'A' = 0(that's why i added a + 1), 'B' - 'A' = 1 and so on.
For the if condition, I am using a RegExp. ^ means start of the input, [A-Z]{1} means one of A-Z, $ means the end of the input. So, if it's an A-Z, temp will get a value, anything else won't make it in the if and your temp will remain 0 so you can easily test if you've got an A-Z or not.
That's all for code review, I won't give you solutions, you must work harder, use Google. You won't enjoy and learn if I give you everything ready for a copy paste.

The program won't print smallest area and perimeter in the figure

I'm trying to print the smallest area and perimeter but all that comes out of the output the the perimeter and area for the circle class. Here is my main method (the for loops are all the way at the bottom):
public static void main (String [] args)//print Figure(Figure[])
{
System.out.println("TESTING FIGURES");
System.out.println("===============\n\n\n");
// form an array of figures
System.out.println("We form an array of 4 figures");
Figure[] set1 = new Figure[4];
set1[0] = new Circle(10);
set1[1] = new Triangle(10, 6, 8);
try
{
set1[2] = new Triangle(5, 12, 7);
}
catch (IllegalArgumentException e)
{
System.out.println("We try to form an illegal triangle");
}
set1[2] = new Parallelogram(10, 20, Math.PI / 3);
set1[3] = new Square(6);
System.out.println("The array is ");
printArray(set1);
// find the figures with the largest area, largest perimeter,
// smallest area, smallest perimeter
Figure smallArea = getSmallestArea(set1);
Figure bigArea = getLargestArea(set1);
Figure smallPerimeter = getSmallestPerimeter(set1);
Figure bigPerimeter = getLargestPerimeter(set1);
// print these figures
System.out.print("\nThe figure with a largest perimeter is ");
printFig(bigPerimeter);
System.out.print("\nThe figure with a smallest perimeter is ");
printFig(smallPerimeter);
System.out.print("\nThe figure with a largest area is ");
printFig(bigArea);
System.out.print("\nThe figure with a smallest area is ");
printFig(smallArea);
}
// print an array of figures
// if the array is null or empty print the message "The array is empty"
// otherwise print 2 lines
// that displays the shape, the fields, the perimeter and the area
// of each item in the array
public static void printArray(Figure[] figs)
{
if(figs == null || figs.length == 0)
{
System.out.println("The array is empty");
}
else
for(int i = 0; i < figs.length; i++)
{
printFig(figs[i]);
}
}
// print the shape, the fields, the perimeter and the area
// of fig
// if fig = null, write null
public static void printFig(Figure fig)
{
if(fig == null)
System.out.println("null");
else
{
if( fig instanceof Circle)
{
System.out.print("a circle of ");
System.out.println( "radius = " + ((Circle)fig).getRadius() );
}
else if (fig instanceof Triangle)
{
System.out.print("a triangle with ");
System.out.println("sides " + ((Triangle)fig).getSide1() + ", " + ((Triangle)fig).getSide2() + ", " + ((Triangle)fig).getSide3());
}
else if (fig instanceof Parallelogram)
{
System.out.print("a parallelogram with ");
System.out.println("sides " + ((Parallelogram)fig).getSide1() + " and " + ((Parallelogram)fig).getSide2() + " and angle of " +
((Parallelogram)fig).getAngle());
}
else if (fig instanceof Square)
{
System.out.print("a square with ");
System.out.println("side= " + ((Square)fig).getSide());
}
System.out.println( "The perimeter is " + fig.getPerimeter( ) + " and the area is " + fig.getArea());
}
}
// return a reference to a figure with the largest perimeter
// among all figures of arr
// if arr is null or empty return null
public static Figure getLargestPerimeter(Figure[] arr)
{
if(arr == null || arr.length == 0)
return null;
Figure bigPerimeter = arr[0];
for(int i = 0; i < arr.length; i++)
{
if(arr[i] != null && arr[i].getPerimeter() > bigPerimeter.getPerimeter())
bigPerimeter = arr[i];
}
return bigPerimeter;
}
// return a reference to a figure with the smallest perimeter
// among all figures of arr
// if arr is null or empty return null
public static Figure getSmallestPerimeter(Figure[] arr)
{
if(arr == null || arr.length == 0)
return null;
Figure smallPerimeter = arr[0];
for(int i = 0; i > arr.length; i++)
{
if(arr[i] != null && arr[i].getPerimeter() < smallPerimeter.getPerimeter())
smallPerimeter = arr[i];
}
return smallPerimeter;
}
// return a reference to a figure with the largest area
// among all figures of arr
// if arr is null or empty return null
public static Figure getLargestArea(Figure[] arr)
{
if(arr == null || arr.length == 0)
return null;
Figure bigArea = arr[0];
for(int i = 0; i < arr.length; i++)
{
if(arr[i] != null && arr[i].getArea() > bigArea.getArea())
bigArea = arr[i];
}
return bigArea;
}
// return a reference to a figure with the smallest area
// among all figures of arr
// if arr is null or empty return null
public static Figure getSmallestArea(Figure[] arr)
{
if(arr == null || arr.length == 0)
return null;
Figure smallArea = arr[0];
for(int i = 0; i > arr.length; i++)
{
if(arr[i] != null && arr[i].getArea() < smallArea.getArea())
smallArea = arr[i];
}
return smallArea;
}
Also my triangle class won't print the sides and i tried to input an IllegalArgumentException but the side still wont print. Here is the code:
public class Triangle implements Figure
{
// the fields
private double a, b, c; // the 3 fields
// the constructor
// form a triangle with sides s1,s2,s3
// if s1,s2,s3 do not form a triangle, throw an
// IllegalArgumentException
public Triangle(double s1, double s2, double s3) //throws IllegalArgumentException
{
s1= a;//hypotenuse
s2= b;//base
s3= c;//height
if(a + b < c || a + c < b || c + b < a)
{
throw new IllegalArgumentException
("We try to form an illegal triangle");
}
}
// methods that return the 3 sides
public double getSide1()
{
return a;
}
public double getSide2()
{
return b;
}
public double getSide3()
{
return c;
}
// # return the perimeter
#Override
public double getPerimeter()
{
return a + b + c;
}
// #return the area
#Override
public double getArea()
{
return (0.5) * b * c;
}
}
The second expression in a for loop means "keep executing the loop AS LONG AS the condition is true" -- not "keep executing UNTIL it's true". This means that if your loop looks like this:
for(int i = 0; i > arr.length; i++)
you will never execute anything in the loop, because i starts out as 0 and 0 > arr.length is false and so the loop stops right away. Change > to <.

Categories

Resources