Reputation: 921
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?
Upvotes: 0
Views: 1048
Reputation: 178461
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.
Upvotes: 1
Reputation: 14338
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));
Upvotes: 3