0

At the input I get a polynomial as a string, for example "7x^4+3x^3-6x^2+x-8". I want to get its coefficients in variables but I have no idea on how to do this. Maximum degree is not known, coefficients are integers. Also terms of some degree can be absent. I will be very grateful for any help.

I tried to split by "+" and "-" and then by "x^" but I have trouble with x, the term with (unwritten) degree 1. Also I have tried firstly split by "x" then by "^" and handled exception with "-" but I don't know how to handle exception with missing degrees.

private fun koef(text: String) : List<Int> {
        val vars = text.split("x")
        val koefList = mutableListOf<Int>()
        var count = 1
        vars.forEach {
            if (it == "-") koefList.add(-1)
            else {
                if (it[0] == '^')
            }
        }
        return koefList
    }
ottomeister
  • 5,415
  • 2
  • 23
  • 27
Marlock
  • 275
  • 2
  • 9
  • Since this is clearly an expanded version of your own https://stackoverflow.com/questions/55183200, is it worth linking to that?  (To prevent folk like me getting déjà vu, if nothing else…) – gidds Mar 30 '19 at 22:34
  • How much do you know about the format of the polynomial?  Are the terms always in reverse numerical order of their powers?  Can any be negative?  And is it strictly required to return a list with each power given by its position in the list, or could you return e.g. a list/set of (power, coefficient) pairs? – gidds Mar 30 '19 at 22:37
  • The degrees of the polynomial go in descending order, the degrees cannot be negative, instead of the missing coefficients should be zeros in list. This is necessary to perform subsequent operations on a polynomial. – Marlock Mar 31 '19 at 01:00
  • The advice from the previous version to which you are referring to me was not possible to realize due to the incorrect conditions set by me. Also, English is not my first language, so sometimes I have to use a dictionary, which additionally leads to misunderstanding. I am very interested in Kotlin, but in my own language there is practically no one worthy resource for this programming language. – Marlock Mar 31 '19 at 01:05

1 Answers1

0

Here's one implementation.

It's slightly more general, allowing the terms to be in any order, and to have surrounding whitespace.  But it still assumes that the polynomial is valid, that the powers are non-negative and all different, and that there's at least one term.

You didn't specify the order of coefficients, so this returns them in increasing power (starting with that of x^0, then x^1, &c).

private fun coeffs(polynomial: String): List<Int> {
    val terms = polynomial.split(Regex("(?=[+-])")).associate{ term ->
        val s = term.split(Regex("x\\^?"))
        val coeff = s[0].replace(" ", "")
                .let{ when (it){ "", "+" -> 1; "-" -> -1; else -> it.toInt() }}
        val power = s.getOrNull(1)?.trim()
                .let{ when (it){ null -> 0; "" -> 1; else -> it.toInt() }}
        power to coeff
    }
    val highestPower = terms.keys.max()!!
    return (0..highestPower).map{ terms[it] ?: 0 }
}

Sample results:

  • coeffs("x^2+2x-1") = [-1, 2, 1]
  • coeffs("2x^3 - 3x^4 - x + 4") = [4, -1, 0, 2, -3]
  • coeffs("x") = [0, 1]
  • coeffs("-2") = [-2]

It starts by splitting the string into terms.  ((?=[+-]) is a lookahead, which matches an empty string if it's followed by + or -.  Full documentation on Java/Kotlin regular expressions is here.)

It then splits each term into a coefficient and power, converts them to numbers, and creates a Map from term to coefficient.  (That's quite awkward, as it has to handle several special cases where the numbers and/or signs are missing.)  Using a map handles missing powers (and also powers that aren't in order).

Finally, it finds the largest power, and converts the map to a list of coefficients in increasing powers, filling in 0 for missing powers.

I've kept the code short, to show the principle.  If it were to be used in production, you should probably make it safer and more efficient, e.g. by checking for invalid input such as empty string, invalid characters, or duplicate powers; and by putting the Regexs in properties so that they don't have to be recreated each time.  Some unit tests wouldn't be a bad thing, either!

gidds
  • 16,558
  • 2
  • 19
  • 26