Dynamically allocating an array from a polynomial function string
So, I have a polynomial addition problem like the following:
(1*x+2*x^3-1*x+7)+(1+1*x^2-1*x+1*x^4)
I need to figure out how to extract numbers for coefficients and measures and inject them into a dynamically allocated 2D array (from here I can sort them and add them together before giving the answer).
I am rather lost on how to do this because polynomials can be in any order of degrees and include any number of terms. I can dynamically allocate them after retrieving all numbers. I need help:
- Extracting all numbers
- Differentiate between them to see if it is a ratio or an indicator
- Let's say this happens for any number of terms.
If anyone can answer this, or at least point me in the right direction, it would be appreciated.
source to share
Your problem looks like its analysis and assessment.
-
Step 1: you need to parse the string assuming infix expression so that you can pull out the coefficient
-
Step2: push these coefficients into vector / deque etc. to perform polynomial calculation.
Here are some good examples:
Evaluating arithmetic expressions from a string in C ++
What is the best way to evaluate mathematical expressions in C ++?
source to share
To extract coefficients from a string, you need to create a parser. You can use a special library like boost.spirit , you can use a special tool that creates parsers like Flex , or you can make your own by hand using regular expressions or not.
To store the coefficients, you can use std::vector<int>
using indices as cardinality of x, so for 1 * x + 2 * x ^ 3-1 * x + 7 your vector will have the data:
{ 7, -1, 0, 2 } // 7*x^0 + -1*x^1 + 0*x^2 + 2*x^3
then you don't need to sort them to add odds. To keep all polynomials, you must use std::vector<std::vector<int>>
accordingly.
source to share