我对 Java 不太精通,如果有人能帮助我解决我遇到的问题,我将不胜感激。
这是我的代码:`
static void sum_up_recursive(ArrayList<Double> numbers, int target, ArrayList<Double> partial) {
double s = 0;
for (double x: partial) s += x;
if ( s <target )
System.out.println("sum("+Arrays.toString(partial.toArray())+ " " +partial.size() +")="+target);
if (s >= target)
return;`
它给了我这个结果
sum([1.3, 0.5, 0.5, 1.3, 0.5, 1.3, 1.3, 0.5, 0.5, 0.5] 10)<=12
sum([1.3, 0.5, 0.5, 1.3, 0.5, 1.3, 1.3, 0.5, 1.3] 9)<=12
sum([1.3, 0.5, 0.5, 1.3, 0.5, 1.3, 1.3, 0.5, 0.5, 0.5] 10)<=12
sum([1.3, 0.5, 0.5, 1.3, 0.5, 1.3, 1.3, 0.5, 1.3] 9)<=12
sum([1.3, 0.5, 0.5, 1.3, 0.5, 1.3, 1.3, 0.5, 1.3, 0.5] 10)<=12
sum([1.3, 0.5, 0.5, 1.3, 0.5, 1.3, 1.3, 0.5, 1.3, 0.5, 1.3] 11)<=12
and so on... There are hundreds if it..
我想做的是将所有这些结果存储在一个多数组中,以便更容易地操作它们,或者也许您知道如何在该循环中对它们进行排序。就像选择元素总和更大的行之一。
谢谢
最佳答案
您可以创建一个同时包含 List
和总和的类:
class Sum {
ArrayList<Double> numbers;
Double total;
}
以及此类的自定义Comparator
class SumComparator implements Comparator<Pair> {
@Override
public int compare(Sum a, Sum b) {
return Double.compare(a.total, b.total);
}
}
然后你可以像这样对 Pair 数组进行排序:
Sum[] sums = new Sum[]; // initialize with values
Arrays.sort(sums, new SumComparator());
这将根据每个 Sum
对象中每个 List
数字的总和对数组或 Sum 进行排序。
关于java - 从循环添加到多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33599179/