0

I'm trying to learn how to code and stumbled upon a problem generating a powerset of a source set in java. I try to write a method that returns a list of lists of doubles for a input of list of doubles. Sadly for a input of

[1.0, 2.0, 3.0]

it only returns

[[], [1.0], [1.0], [1.0, 2.0], [1.0], [1.0, 3.0], [1.0, 2.0], [1.0, 2.0, 3.0]]

so there has to be a matter with my for-loops. After hours of trying to find different ways of arranging the code, im stuck. Can someone spot the mistake i'm making for me? I would also appreciate some feedback on what I could improve on regarding usage of types/coding in general.

Thanks a lot!

Edit: had the wrong code in it

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;
    }
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214

1 Answers1

-1

You are not considering that the indexing of a string is counted from the left side. You need to subtract i from the last index of the binary string. Fix to your code is as follows.

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;
    }
Chamal Perera
  • 313
  • 1
  • 2
  • 10