【问题标题】:Find powersets for a given set查找给定集合的幂集
【发布时间】: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;
    }

【问题讨论】:

    标签: java powerset


    【解决方案1】:

    您没有考虑字符串的索引是从左侧开始计算的。您需要从二进制字符串的最后一个索引中减去 i。 修复您的代码如下。

    private static List<?> genSubset(List<Double> set, int size) {
            List<List<Double>> subsets = new ArrayList<List<Double>>();
    
            for (int x = 0; x < Math.pow(2, size); x++) {
    
                List<Double> currentSet = new ArrayList<Double>();
                String binString = Integer.toBinaryString(x);
                for (int i = 0; i < size; i++) {
                    if (binString.length() > i && binString.charAt(binString.length()-i-1) == '1') {
                        currentSet.add(set.get(i));
                    }
                }
                subsets.add(currentSet);
    
            }
    
            return subsets;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多