简体   繁体   English

如何将字符串转换为多项式并加上或减去它们?

[英]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 我必须将多项式表示为arrayslist。如何从类似于此的txt文件中获取输入

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 ? 比如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 SO P1 = 5X ^ 3 - 4X + 8

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

becomes

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

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

____________________________________ ____________________________________

SUM= 6X^5 + 5X^3 -2X^2 + 3X^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 您可以将权力存储为Key,将系数作为值存储在Map中。然后迭代地图并在其值中添加系数

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 EDITED for multiple Polynomials.Multiple Polynomials在List中添加,然后sum通过迭代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: 现在,创建一个Polynomial类作为术语List ,并定义添加和删除术语的必要方法:

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. 例如, Term可以实现Comparable<Term>以支持术语之间的比较,类似于Polynomial和其他元素。

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. 我能想到的最简单的解决方案是将系数存储在一个数组中,并让数组的索引对应于x项上的x 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. 所以n阶多项式将有一个大小为n + 1的数组来表示它。

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. 从这里,您可以获得所需的变量,并通过获取arraylist的索引来计算值,并使用一些魔法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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