C++ extract polynomial coefficients

前端 未结 5 1337
迷失自我
迷失自我 2021-01-26 01:38

So I have a polynomial that looks like this: -4x^0 + x^1 + 4x^3 - 3x^4
I can tokenize this by space and \'+\' into: -4x^0, x^1, 4x^3, -, 3x^4

How could I just get t

5条回答
  •  一向
    一向 (楼主)
    2021-01-26 02:09

    Write a simple tokenizer. Define a number token (/[-0123456789][0123456789]+/), an exponent token (/x^(::number::)/). Ignore whitespace and +.

    Continually read tokens as you'd expect them until the end of the string. Then spit out the tokens in whatever form you want (e.g. integers).

    int readNumber(const char **input) {
        /* Let stdio read it for us. */
        int number;
        int charsRead;
        int itemsRead;
    
        itemsRead = sscanf(**input, "%d%n", &number, &charsRead);
    
        if(itemsRead <= 0) {
            // Parse error.
            return -1;
        }
    
        *input += charsRead;
    
        return number;
    }
    
    int readExponent(const char **input) {
        if(strncmp("x^", *input, 2) != 0) {
            // Parse error.
            return -1;
        }
    
        *input += 2;
    
        return readNumber(input);
    }
    
    /* aka skipWhitespaceAndPlus */
    void readToNextToken(const char **input) {
        while(**input && (isspace(**input) || **input == '+')) {
            ++*input;
        }
    }
    
    void readTerm(const char **input. int &coefficient, int &exponent, bool &success) {
        success = false;
    
        readToNextToken(input);
    
        if(!**input) {
            return;
        }
    
        coefficient = readNumber(input);
    
        readToNextToken(input);
    
        if(!**input) {
            // Parse error.
            return;
        }
    
        exponent = readExponent(input);
    
        success = true;
    }
    
    /* Exponent => coefficient. */
    std::map readPolynomial(const char *input) {
        std::map ret;
    
        bool success = true;
    
        while(success) {
            int coefficient, exponent;
    
            readTerm(&input, coefficient, exponent, success);
    
            if(success) {
                ret[exponent] = coefficient;
            }
        }
    
        return ret;
    }
    

    This would probably all go nicely in a class with some abstraction (e.g. read from a stream instead of a plain string).

提交回复
热议问题