【发布时间】:2021-03-01 21:24:05
【问题描述】:
我正在尝试学习如何编写代码,但偶然发现了在 java 中生成源集的 powerset 的问题。 我尝试编写一个方法,该方法返回一个双打列表的列表作为双打列表的输入。可悲的是输入
[1.0, 2.0, 3.0]
它只会返回
[[], [1.0], [1.0], [1.0, 2.0], [1.0], [1.0, 3.0], [1.0, 2.0], [1.0, 2.0, 3.0]]
所以我的 for 循环肯定有问题。经过数小时试图找到安排代码的不同方式后,我陷入了困境。有人能发现我为我犯的错误吗?对于一般类型/编码的使用我可以改进哪些方面的反馈,我也将不胜感激。
非常感谢!
编辑:里面有错误的代码
private static List<?> genSubset(List<Double> set, int size){
List<List<Double>> subsets = new ArrayList<List<Double>>();
System.out.println(set);
for (int x=0; x<Math.pow(2,size); x++)
{
List<Double> currentSet = new ArrayList<Double>();
for (int i = 0; i<size; i++){
try {if (Integer.toBinaryString(x).charAt(i)=='1'){
currentSet.add(set.get(i));
}
}
catch (Exception e){}
}
subsets.add(currentSet);
}
return subsets;
}
【问题讨论】: