1つのdouble配列と1つの値を与えて、配列の中のいくつかの数の和が与えられた値に等しいことを求めます
17261 ワード
1つのdouble配列と1つの値を与えて、配列の中のいくつかの数の和が与えられた値に等しいことを求めます
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
//
double[] doubles = {1.11, 2.22, 3.33, 4.44, 5.55, 6.66, 7.77, 8.88, 9.99};
List<List<Double>> lists = calculate(doubles, 9.99);
for (List<Double> list : lists) {
for (Double aDouble : list) {
System.out.print(aDouble + " ");
}
System.out.println();
}
}
/***
* double , 。
* @param doubles
* @param dn
* @return
*/
public static List<List<Double>> calculate(double[] doubles, Double dn) {
List<Double> list = new ArrayList<>(doubles.length);
for (double aDouble : doubles) {
list.add(aDouble);
}
List<List<Double>> ret = new ArrayList<>();
int a = 1, c = 1;
List<Double> d;
for (int i = 0; i < list.size(); i++) {
double s = list.get(i);
//StringBuffer str = new StringBuffer(list.get(i) + "+");
boolean bb = true;
while (bb) {
if (bb = false) {
break;
}
if (list.size() == a) {
break;
}
while (true) {
if (list.size() == c) {
a++;
c = a;
break;
}
d = new ArrayList<>();
d.add(list.get(i));
for (int j = c; j < list.size(); j++) {
s = add(s, list.get(j));
d.add(list.get(j));
//str.append(list.get(j) + "+");
//System.out.println(str.substring(0, str.length() - 1));
String d1 = Double.toString(s);
String d2 = Double.toString(dn);
if (d2.equals(d1)) {
ret.add(d);
break;
}
if (list.size() - j == 1) {
s = list.get(i);
//str = new StringBuffer(list.get(i) + "+");
c++;
break;
}
}
}
}
}
return ret;
}
private static double add(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}
}