简体   繁体   中英

How to convert Strings into polynomials and adding or subtracting them?

I have to represent the polynomials as arrayslist.How to take input from a txt file that looks like this

P1;5;3;-4;1;8;0
P2;6;5;-2;2;7;1;-4;0

and turn it into a polynomial that look like this

P1(X) = 5X^3 –4X +8
P2(X) = 6X^5 -2X^2 +7X -4.

And how could I solve addition and subtraction problems between these two polynomials? such as P1 + P2 ?

here is what i have:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;


public class PolyProcessor {
    static int polyNum = 0;
public static void main(String[] args) throws FileNotFoundException{

    PolyCalc c = new PolyCalc();
    File polyfile = new File("polyinput.txt");
    Scanner read = new Scanner(polyfile);
    while (read.hasNextLine()){
        String j = read.nextLine();
        c.add(j);
        }


    }
    }


class PolyCalc{
    static int polyCount = 0;

    static ArrayList polynomials = new ArrayList();

     static void add(String j){

         polynomials.add(j);
         polyCount++;}

     static Object get(int i){
         return polynomials.get(i);}


    }

How does polynomial addition work?

Answer:- By adding the coefficients of same power

SO P1 = 5X^3 - 4X + 8

and P2 = 6X^5 -2X^2 + 7X^1 + -4

becomes

P1 = 0X^5 + 5X^3 +0X^2 - 4X^1 + 8X^0

P2 = 6X^5 + 0X^3 -2X^2 + 7X^1 - 4X^0

____________________________________

SUM= 6X^5 + 5X^3 -2X^2 + 3X^1 + 4X^0

____________________________________

You can store the power as Key and coefficient as value in a Map.Then iterate the maps and add the coefficients in their value

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

class SumOfPolynomials {

/**
 * @param args
 * @throws FileNotFoundException 
 */
public static void main(String[] args) throws FileNotFoundException {

     List<Map<Integer, Integer>> listOfPolynomials = new ArrayList<Map<Integer, Integer>>();
    File polyfile = new File("polyinput.txt");
    Scanner read = new Scanner(polyfile);
    while (read.hasNextLine()){
        String LINE = read.nextLine();
        String[] lineSpillted =LINE.split(";");
        Map<Integer, Integer> poynomial = new HashMap<Integer, Integer>();
        for(int i =1;i<lineSpillted.length-1;i=i+2){                //i starts from ignores P1,P2 etc

             poynomial.put(Integer.parseInt(lineSpillted[i+1]), Integer.parseInt(lineSpillted[i]));

        }
        listOfPolynomials.add(poynomial);
        }

    read.close();

    Map<Integer, Integer> result = polynomialSum(listOfPolynomials.get(0), listOfPolynomials.get(1));

    if(listOfPolynomials.size()>2){

        for(int i=2;i<listOfPolynomials.size()-1;i++){

            result = polynomialSum(result,listOfPolynomials.get(i));
        }
    }
    // print out the SUM as VALUEX^KEY
    System.out.println();
    int c = 0;
    for (Map.Entry<Integer, Integer> entry : result.entrySet()) {

        System.out.print(entry.getValue() + "X^" + entry.getKey());
        c++;
        if (c != result.size()) {
            System.out.print("+");
        }
    }

}

public static Map<Integer, Integer> polynomialSum(Map<Integer, Integer> arg1,
        Map<Integer, Integer> arg2) {

    Map<Integer, Integer> SUM = new HashMap<Integer, Integer>();

    for (Map.Entry<Integer, Integer> entry : arg1.entrySet()) {

        Integer power = entry.getKey();
        Integer coeff1 = entry.getValue();
        Integer coefficient;
        if (arg2.containsKey(power)) {
            coefficient = arg2.get(power) + coeff1;
        } else {
            coefficient = coeff1;
        }
        SUM.put(power, coefficient);
    }

    for (Map.Entry<Integer, Integer> entry : arg2.entrySet()) {

        if (SUM.containsKey(entry.getKey())) {
            continue;
        } else {
            SUM.put(entry.getKey(), entry.getValue());
        }

    }

    return SUM;
}

}

EDITED for multiple Polynomials.Multiple Polynomials are added in a List and then sum is calculated by iterating the List

Output:-

产量

Here's an idea about how to implement the polynomial:

Based on the definition of polynomial :

In mathematics, a polynomial is an expression consisting of variables (or indeterminates) and coefficients, that involves only the operations of addition, subtraction, multiplication, and non-negative integer exponents.

So, you can start by reducing the problem to a term:

class Term {
    //making it immutable
    final double power;
    final double coefficient;
    final String variable;
    //constructor
    public Term(double power, double coefficient, String variable) {
        //assign variables and such
        this.power = power;
        //...
    }
    //getters for your class
}

Now, create a Polynomial class as a List of terms and define necessary methods to add and remove terms:

class Polynomial {
    final String variable;
    List<Term> terms;
    public Polynomial(String variable) {
        //this will allow you to accept only "X" or "Y" or terms with this variable only
        this.variable = variable;
        terms = new ArrayList<Terms>();
    }
    public void add(Term term) {
        /*
            implement this...
        */
    }
}

With this basic model, you can come up with more ideas to enhance the design. For example, Term can implement Comparable<Term> in order to support comparison between terms, similar for Polynomial and other elements.

The simplest solution I can think of is to store the coefficients in an array, and let the indices of the array correspond to the powers on the x term. So an array of:

{2, 4, -1, 1}

Would translate to:

x^3 - x^2 + 4x + 2

Then adding and subtracting would simply be a matter of adding corresponding indices between two arrays, and storing the result in a new array. You would also have to keep track of the highest power term of the polynomial so you would know how how big to make the array that represents it. So a polynomial of order n would have an array of size n + 1 to represent it.

Sorry about the variable names not being anything close to being mathematical standards nor has this been tested, but this should leave you with some sort of idea.

import java.util.ArrayList;
public class Poly {

    private String[] numbers;
    private ArrayList<Variable> func;

    public Poly(String poly, double valueOfX) {
        numbers = poly.split(";");
        func = new ArrayList<>();
        for (int i = 1; i < numbers.length - 1; i+=2) {
            double exp = (numbers[i+1] == "0") ? 1 : Double.parseDouble(numbers[i++]); 
            double x = (numbers[i+1] == "0") ? 1 : valueOfX; 
            func.add(new Variable(Double.parseDouble(numbers[i]), exp, x));
        }
    }

    public ArrayList<Variable> getFunc() {
        return func;
    }

}
public class Variable {

    private double value;
    private double exponent;
    private double x;

    public Variable(double value, double exponent, double x) {
        this.value = value;
        this.exponent = exponent;
        this.x = x;
    }

    public double getValue() {
        return value;
    }

    public double getExponent() {
        return exponent;
    }

    public double getX() {
        return x;
    }
}

From this, you are then able to get the variables you want and calculate values by getting the index of the arraylist and work some magic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM