简体   繁体   中英

Java: Add all possible combinations of TRUE/FALSE to a list

I have seen other posts about this, but they are not exactly like this problem.

I have this code:

    public static List<Boosters.Builder> GetBoosters() {
    List<Boosters.Builder> boosters = new ArrayList<Boosters.Builder>();

    Boosters.Builder booster = new Boosters.Builder();

    booster.setLarge(Bool.TRUE).setMedium(Bool.TRUE).setSmall(Bool.TRUE);
    boosters.add(booster);

    booster.setLarge(Bool.FALSE).setMedium(Bool.TRUE).setSmall(Bool.FALSE);
    boosters.add(booster);

    booster.setLarge(Bool.TRUE).setMedium(Bool.FALSE).setSmall(Bool.TRUE);
    boosters.add(booster);

    booster.setLarge(Bool.TRUE).setMedium(Bool.TRUE).setSmall(Bool.FALSE);
    boosters.add(booster);

    // (etc, etc, etc)

    return boosters;
}

Which is a part of some generated types I am doing in Java. But Bool.TRUE/Bool.FALSE works sort of like normal java booleans so you can count on that.

I am trying to make a loop that will give me all possible combinations of TRUE/FALSE on:

booster.setLarge(Bool.TRUE).setMedium(Bool.TRUE).setSmall(Bool.TRUE);

I cannot figure out how to do this nicely in a loop. Can someone help me out?

Use Bool#values() to iterate over possible values of your enum:

for (Bool large : Bool.values())
   for (Bool medium : Bool.values())
        for (Bool small : Bool.values())
              boosters.add(new Boosters.Builder().setLarge(large).setMedium(medium).setSmall(small));

One approach would be to run an integer from 0 to 2^n (exclusive) - where n is the number of variables you need to assign.

Then, you can use (x >> k) % 2 to get the value of variable number k.

This works only for having less than 64 values (using long variables).

       for (int x =0; x < 1<<k; x++) { 
            int val1 = (x >> 0) %2;
            int val2 = (x >> 1) %2;
            int val3 = (x >> 2) %2;
            ...
            System.out.println("" + val1 + "," + val2 + "," + val3);
        }

Note that this approach can be easily modified to any number of variables (that fits in long ) you have, by switching val1,val2,... to an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM