用Java实现PowerSets

时间:2017-03-07 20:08:15

标签: java powerset

import java.util.*;

public class BruteForce {
    static int numObject;
    static int weightThreshold = 0;
    static double numCombination;
    static BruteForce knapsack = new BruteForce();
    static Scanner input = new Scanner(System.in);

    public static void main(String args[]) {
        System.out.print("Enter weight threshold: ");
        weightThreshold = input.nextInt();
        System.out.print("Enter number of objects: ");
        numObject = input.nextInt();

        String[] variables = new String[numObject];
        int[] weightObject = new int[numObject];
        int[] costObject = new int[numObject];
        Random rand = new Random();
        Random r = new Random();

        for (int i = 0; i < numObject; i++) {
            char temp = (char) (r.nextInt(26) + 'a');
            variables[i] = Character.toString(temp);
        }
        System.out.println("Variables Array: " + Arrays.toString(variables));
        for (int i = 0; i < numObject; i++) {
            int n = rand.nextInt(50) + 1;
            weightObject[i] = n;
        }
        System.out.println("Weights Array: " + Arrays.toString(weightObject));
        for (int i = 0; i < numObject; i++) {
            int n = rand.nextInt(100) + 25;
            costObject[i] = n;
        }
        System.out.println("Cost Array: " + Arrays.toString(costObject));

        knapsack.possibleCombinations(variables, weightObject, costObject, weightThreshold, numObject);
    }

    public void possibleCombinations(String variables[], int weightObject[], int costObject[], int weightThreshold,
            int numObject) {

        for (int i = 0; i < (1 << numObject); i++) {
            int weight = 0;
            int cost = 0;
            System.out.print("{ ");
            // Print current subset
            for (int j = 0; j < numObject; j++){

                if ((i & (1 << j)) > 0) {
                    weight += weightObject[j];
                    cost += costObject[j];
                    System.out.print(variables[j] + " ");
                }
            }
            System.out.println("}");
            System.out.print("\t" + weight + "\t" + cost);
        }
    }

}

我正在尝试实施PowerSet。我正试图用蛮力解决背包问题。所以我必须创建集合的所有子集,并为每个集合添加权重和值。选择maxWeight下具有最高值的权重。

我只是在制作所有套装。我可以创建所有变量子集,但我无法正确添加子集的权重和值。这是我的输出:

Enter weight threshold: 1
Enter number of objects: 3
Variables Array: [w, b, x]
Weights Array: [29, 42, 42]
Cost Array: [55, 96, 38]
{ }
    0   0{ w }
    29  55{ b }
    42  96{ w b }
    71  151{ x }
    42  38{ w x }
    71  93{ b x }
    84  134{ w b x }
    113 189

我不知道我的循环出错了。 w的值为零(当然是错误的),然后所有其他变量都没有相应的值。我究竟做错了什么?另外,我承认我从一个网站获得了PowerSet循环,但我不知道为什么循环适用于变量,但没有加入权重和值。

0 个答案:

没有答案