netbeans - Inserting an object in ascending order with an ArrayList in Java -
so i've went , forth quite few times trying multiple different methods can't seem wrap head around appropriate algorithm method. creating polynomial class uses arraylist term(int coeff, int expo) coeff coefficient of polynomial , expo exponent. in test class have insert multiple different term objects need inserted in ascending order exponents (for example, 4x^1 + 2x^3 + x^4 + 5x^7)
this code have end of insert() method takes 2 parameters, coeff , expo:
public class polynomial { private arraylist<term> polynomials ; /** * creates new polynomial object no terms */ public polynomial() { polynomials = new arraylist<>() ; } /** * inserts new term proper place in polynomial * @param coeff coefficient of new term * @param expo exponent of new term */ public void insert(int coeff, int expo) { term newterm = new term (coeff, expo) ; if (polynomials.isempty()) { polynomials.add(newterm); return; } int polysize = polynomials.size() - 1 ; (int = 0 ; <= polysize ; i++) { term listterm = polynomials.get(i) ; int listtermexpo = listterm.getexpo() ; if ( expo <= listtermexpo ) { polynomials.add(i, newterm); return; } else if ( expo > listtermexpo ) { polynomials.add(newterm) ; return ; } } }
the problem arises near end of code. once put in term coefficient isn't <= term @ index goes else if statement , adds end of list. wrong, since needs added becomes bigger next coefficient. because it's larger coefficient doesn't mean largest coefficient. i've tried doing statement backwards where:
for (i = polysize ; >= 0 ; i--) { etc. }
but didn't work either since raises same issue other way around. if provide solution or answer appreciated since confused. @ point i'm sure i'm making complicated. want know how recognize exponent larger go loop until smaller or equal index's exponent.
also, should mention, not allowed use other collection or class, must using for, if, else, or while statement. in advance!
remove loop:
else if (expo > listtermexpo) { polynomials.add(newterm); return; }
place after loop:
polynomials.add(newterm); return;
reasoning: want add term end of list if not less term in - not first term.
also, formatting have ; after statement no space in between, , ()s not have spaces inside them. i've edited code copied show mean.
Comments
Post a Comment