0

I am trying to write a program that can find the roots of a quadratic equation using Scala. The input should be a quadratic equation in the form ax^2+bx+c (e.g: 5x^2+2x+3) as a string.

I managed to code the calculation of the roots but am having trouble extracting the coefficients from the input. Here's the code I wrote for extracting the coefficients so far:

def getCoef(poly: String) = {
  var aT: String = ""
  var bT: String = ""
  var cT: String = ""
  var x: Int = 2
  for (i <- poly.length - 1 to 0) {
    val t: String = poly(i).toString
    if (x == 2) {
      if (t forall Character.isDigit) aT = aT + t(i)
      else if (t == "^") {i = i + 1; x = 1}
    }
    else if (x == 1) {
      if (t forall Character.isDigit) bT = bT + t(i)
      else if (t == "+" || t == "-") x = 0
    }
    else if (x == 0) {
      if (t forall Character.isDigit) cT = cT + t(i)
    }
  val a: Int = aT.toInt
  val b: Int = bT.toInt
  val c: Int = cT.toInt
  (a, b, c)
  }
}
  • Have you thought about using regex? Not sure how complex your input strings can get, but your problem is parsing and there are excellent solutions for it, like regex or maybe Scala parser combinators. – stholzm Mar 16 '17 at 07:25
  • str.split('x').map(v => v.replace("^2","")).map(_.toDouble) – FatTail Mar 16 '17 at 15:05
  • if your not so keen in regex, and your input is as you describe. – FatTail Mar 16 '17 at 15:06

1 Answers1

0

Simple solution with regex:

def getCoef(poly: String) = {
  val polyPattern = """(\d+)x\^2\+(\d+)x\+(\d+)""".r
  val matcher = polyPattern.findFirstMatchIn(poly).get
  (matcher.group(1).toInt, matcher.group(2).toInt, matcher.group(3).toInt)
}

Does not handle all cases (e.g.: minus) and just throws an error if the input does not match the pattern, but it should get you going.

stholzm
  • 3,395
  • 19
  • 31