簡體   English   中英

如何將字符串轉換為多項式並加上或減去它們?

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

我必須將多項式表示為arrayslist。如何從類似於此的txt文件中獲取輸入

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

並將其轉換為看起來像這樣的多項式

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

我怎樣才能解決這兩個多項式之間的加法和減法問題? 比如P1 + P2

這是我有的:

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);}


    }

多項式加法如何工作?

答案: - 通過添加相同功率的系數

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

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

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

____________________________________

您可以將權力存儲為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在List中添加,然后sum通過迭代List計算

輸出: -

產量

以下是關於如何實現多項式的想法:

基於多項式的定義:

在數學中,多項式是由變量(或不確定)和系數組成的表達式,其僅涉及加法,減法,乘法和非負整數指數的運算。

因此,您可以從將問題減少到一個術語開始:

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
}

現在,創建一個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...
        */
    }
}

有了這個基本模型,您可以提出更多想法來增強設計。 例如, Term可以實現Comparable<Term>以支持術語之間的比較,類似於Polynomial和其他元素。

我能想到的最簡單的解決方案是將系數存儲在一個數組中,並讓數組的索引對應於x項上的x 所以一組:

{2, 4, -1, 1}

將翻譯為:

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

然后添加和減去只是在兩個數組之間添加相應的索引,並將結果存儲在一個新數組中。 您還必須跟蹤多項式的最高冪項,以便了解如何使用代表它的數組。 所以n階多項式將有一個大小為n + 1的數組來表示它。

很抱歉變量名稱沒有任何接近於數學標准,也沒有經過測試,但這應該讓你有一些想法。

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;
    }
}

從這里,您可以獲得所需的變量,並通過獲取arraylist的索引來計算值,並使用一些魔法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM