Skip to content

Instantly share code, notes, and snippets.

@jingz8804
Last active August 29, 2015 14:04
Show Gist options
  • Save jingz8804/cd024335b99bc2fcb044 to your computer and use it in GitHub Desktop.
Save jingz8804/cd024335b99bc2fcb044 to your computer and use it in GitHub Desktop.
public class ExpressionTerm implements Comparable{
double coefficient;
double exponent;
// getter and setter
public int compareTo(ExpressionTerm term){
if (this.exponent < term.exponent) return -1;
if (this.exponent == term.exponent) return 0;
if (this.exponent > term.exponent) return 1;
}
public ExpressionTerm add(ExpressionTerm term){
// here we should also check if both terms have the same exponent
// if not we should throw expcetions.
ExpressionTerm result = new ExpressionTerm();
result.coefficient = this.coefficient + term.coefficient;
result.exponent = this.exponent;
return result;
}
}
import java.util.Arrays;
public class PolynomialAddition{
public ExpressionTerm[] sum(ExpressionTerm[] exp1, ExpressionTerm[] exp2){
if(exp1 == null) return exp2;
if(exp2 == null) return exp1;
Arrays.sort(exp1);
Arrays.sort(exp2);
// if there are terms with the same exponents but not merged together
// we could implement another function to merge them
// exp1 = mergeTermsWithSameExponent(exp1);
// exp2 = mergeTermsWithSameExponent(exp2);
int len1 = exp1.length;
int len2 = exp2.length;
// merge the two expressions together into a new one
int len = len1 > len2 ? len1 : len2;
ExpressionTerm[] total = new ExpressionTerm[len];
int i = 0;
int j = 0;
int k = 0;
while(i < len1 && j < len2){
total[k++] = exp1[i++].add(exp2[j++]);
}
if(i == len1){
while(j < len2) total[k++] = exp2[j++];
}else{
while(i < len1) total[k++] = exp2[i++];
}
return total;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment