3

I have created a polynomial class without using Polynomial, I am using my own Term(coefficient, exponent) to create the polynomial expression.

I have some conditions which are as follows:

coefficient = 0 -> Term(0,2) -> 0x^2 -> "0"
coefficient = 1 -> Term(1,2) -> 1x^2 -> "x^2"
coefficient = -1 -> Term(-1,2) -> -1x^2 -> "-x^2"
exponent = 1 = -> Term(5,1) -> 5x^1 -> "5x"
exponent = 0 = -> Term(5,0) -> 5x^0 -> "5"

But implementing all of these to function in and around each other is causing me a massive headache, for example if I have Term(-1,1) I would like "-x" to appear, and "x" for Term(1,1). Can anyone help with thinking of some sort of logic to group all of these "rules" together for a toString method?

germainelol
  • 3,231
  • 15
  • 46
  • 82

5 Answers5

1

The order is important here. If you think it through, you will see that coefficient = 0 should go first, since when it is zero nothing else matters. Next are the special cases for when the exponent equals 1 or 0. Then you have when the coefficient is -1. All that is left then is the default case of either a negative coefficient other than -1 or a positive coefficient. So the if statement should look like:

public String toString() {
    if(coefficient == 0){
      return "0";
    } else if ( coefficient == 1 && exponent != 0){
        return "x^"+exponent; 
    } else if ( exponent == 1){
      return coefficient+"x"; 
    } else if ( exponent == 0){
      return ""+coefficient; 
    } else if ( coefficient == -1){
      return "-x^"+exponent; 
    } else {
      return coefficient+"x^"+exponent; 
    }
}
Jacob Schoen
  • 14,034
  • 15
  • 82
  • 102
1

You can combine the first special case with the last one. You can also combine the second and third cases by looking at the abs value of the coefficient.

// If the coefficient is zero or the exponent is zero,
// the result is simply the coefficient:
if (c == 0 || e == 0) {
    return ""+c;
}
StringBuilder res = new StringBuilder();
// Do not print the number for the coefficient of +/- 1
if (Math.abs(c) == 1) {
    // For +1 do not print the sign either
    if (c == -1) {
        res.append("-");
    }
} else {
    res.append(c);
}
res.append("x");
// For exponent of 1, do not print ^1
if (e != 1) {
    res.append("^");
    res.append(e);
}
return res.toString();
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • I like the idea of using StringBuilder for this, when thinking the different rules through logically, it is a case of building a string to represent the polynomial expression as you go along which is what you have done. I don't like the idea of having hundreds of if statements as it is just confusing to look at so thank you. – germainelol Nov 16 '12 at 21:22
1

This is as close as I got to to make it clear

public class Term { 
    private final int coefficient;
    private final int exponent;

    public Term (final int coefficient,final int exponent) {
        this.coefficient = coefficient;
        this.exponent = exponent;           
    }

    @Override
    public String toString() {
        final String sign = getSign (coefficient);
        final String number = getNumber (coefficient);
        final String exponentStr = getExponentStr (coefficient, exponent);

        return String.format ("%s%s%s",sign, number, exponentStr);
    }

    private String getExponentStr(final int coefficient, final int exponent) {
        if (coefficient == 0 || exponent == 0) {
            return "";
        }
        if (exponent == 1) {
            return "x";
        }
        return "x^" + exponent;
    }

    private String getNumber(final int value) {
        final int absValue = Math.abs(value);

        return absValue == 1 ? "" : Integer.toString (absValue);
    }

    private String getSign(final int value) {
        return value < 0 ? "-" : "";
    }

    public static void main(String[] args) throws Exception {
        System.out.println(new Term (0, 2));
        System.out.println(new Term (1, 2));
        System.out.println(new Term (-1, 2));
        System.out.println(new Term (5, 1));
        System.out.println(new Term (5, 0));
    }
}

And a fiddle for it.

ShyJ
  • 4,560
  • 1
  • 19
  • 19
1

I think, you don't expo will not be negative. Try something as below:

@Override
public String toString() {
    if(coef ==0){
        return "0";
    }else if(expo ==0){
        return ""+coef;
    }else{
        String pref = coef==1? "": coef==-1?"-":""+coef; 
        String suff = expo>1? "^"+expo:""; 
        return pref+"x"+suff;
    }
}

EDIT: To use StringBuilder, change last statement as below(I don't see much benefit though)

   return new StringBuilder(pref).append("x").append(suff).toString();
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
  • This will return `1` for `Term(5,0)`. `5` is the right value, because `5*x^0` is `5*1` is `5`, not `1`. – Sergey Kalinichenko Nov 16 '12 at 21:17
  • @dasblinkenlight: I got confused with x and simple powers. Updated the answer. Please check and let me know, if there is any gap left. To me it looks working fine. – Yogendra Singh Nov 16 '12 at 21:24
  • `5x^0` is representing `5 * x^0`, so while `x^0` is indeed 1, `5*1 = 5` – germainelol Nov 16 '12 at 21:24
  • @user1828314: Yes, I understood. I already updated the answer. Please check and let me know, if there is any gap left. To me it looks working fine. – Yogendra Singh Nov 16 '12 at 21:25
  • @YogendraSingh Yes this gives errors, for example test number one is (-7,0), which should print "-7", but yours is printing "1". – germainelol Nov 16 '12 at 21:28
  • @user1828314: I think you took the older code when I returned 1 when expo was 0. **It was modified**. Please refer the updated answer. This gives me `-7` as you are expecting. – Yogendra Singh Nov 16 '12 at 21:30
  • @YogendraSingh Thanks, this code works now. The question now is which do I use from your answer and the answer using StringBuilder...they both use the same logic I suppose so either one will do so long as they are well documented. – germainelol Nov 16 '12 at 21:33
  • @user1828314: `StringBuilder` is better **when you have multiple concatenations**. In this example, we have max 2(in the last return statement). I will personally not use StringBuilder for such simple concatenation. – Yogendra Singh Nov 16 '12 at 21:38
  • @user1828314: I updated the answer with `StringBuilder` version as well but as I said, I don't see much benefit here. – Yogendra Singh Nov 16 '12 at 21:43
0

Hmmm there really isn't much you can do to make it easier. you essentially have the following cases:

Coefficient = 0 --> Display 0 (exponent irrelevant)
Coefficient = +/- 1 --> Display - if -1 (special case of (-1,0)), nothing otherwise
Other Coefficients --> Display as stored

Exponent = 0 --> display nothing
Otherwise, display x^exponent...

So.....

public String toString() {
  String term = "";

  if (coefficient == 0) {
    return "0";
  } elseif (coefficient == -1) {
    if (exponent == 0) {
      return "-1";
    } else {
      term += "-";
    }
  } elseif (coefficient != 1) {
    term += String.valueOf(coefficient);
  } else {
    if (exponent == 0) {
      return "1";
    }
  }

  if (exponent != 0) {
    if (exponent == 1) {
      term += "x";
    } else {
      term += "x^" + String.valueOf(exponent);
    }
  }

  return term;
}

I think that covers it? I didn't put it through UnitTest to really be sure.

Grambot
  • 4,370
  • 5
  • 28
  • 43