将数组表示为多项式



这个方法应该做的是将一个双精度数组转换成一个多项式,例如,如果给定的数组是[2.0, 3.0, -2.0],该方法的输出将是2.0x^2 + 3.0x^1 - 2.0。我所做的是创建两个循环,然而,当我这样做时,两个输出都像预期的那样分开。我的输出看起来像这样2.0 1.0 2.0 1.0 x^3 x^2 x^1,如果有一种方法可以在系数之后打印指数,可以解决这个问题。

public String printPoly(Double[] doubles) {
String polynomialString = "";
for (int i = 0; i < doubles.length; i++) {
polynomialString += doubles[i] + " ";
}
for (int j = doubles.length - 1; j >= 0; j--) {
if (j == 0) {
polynomialString += " ";
break;
}
polynomialString += "x^" + j + " ";
}
return polynomialString;
}

您可以使用一个for循环来构建resultString。初始化一个计数器变量,你向后计数它代表你的^3部分。该变量从数组开始。长度-1end在迭代中运行到零,这就是您可以创建

的方式
4.0 x^3
2.0 x^2
0.5 x^1
2.0 x^0

它基本上是向后运行的所以你应该在每次迭代中递减

int backCounter = doubles.length-1;

在for循环中执行

polynomialString += doubles[j] + "x^" + backCounter + " ";
backCounter--;

这是一个可行的解决方案

package so;
import java.util.*;
public class RemoveString {
public static void main(String[] args) {
Double[] someNumbers = { 2.0, 3.0, 1.0, 0.5 };
String s = RemoveString.printPoly(someNumbers);
System.out.println(s);
}
public static String printPoly(Double[] doubles) {
String polynomialString = "";
int backwardsCounter = doubles.length - 1;
for (int i = 0; i < doubles.length; i++) {
polynomialString += doubles[i] + "x^" + backwardsCounter + " ";
backwardsCounter --;
}
return polynomialString;
}
}

产生输出

2.0x^3 3.0x^2 1.0x^1 0.5x^0 

一个循环就足够了,或者一个:

public static void main(String[] args) {
System.out.println(printPoly(new double[]{2.0, 3.0, -2.0}));
// 2.0x^2 + 3.0x^1 - 2.0
System.out.println(printPoly(new double[]{-2.0, 3.6, -2.1, 5.2}));
// -2.0x^3 + 3.6x^2 - 2.1x^1 + 5.2
}
public static String printPoly(double[] doubles) {
return IntStream
// iterate through the array indices
.range(0, doubles.length)
// string representation of the coefficient
.mapToObj(i -> coefficient(i, doubles))
// concatenate into one string
.collect(Collectors.joining());
}
// separate method because inside the lambda it is too big
static String coefficient(int i, double[] doubles) {
String val = "";
// take value from an array
double element = doubles[i];
if (i == 0) {
// first element
val += element;
} else {
// other elements
if (element <= 0.0D) {
val += " - " + (0.0D - element);
} else {
val += " + " + element;
}
}
// if non-last element, then
// raised to the power of
if (i < (doubles).length - 1) {
// inverted index
val += "x^" + (doubles.length - 1 - i);
}
return val;
}

最新更新