简体   繁体   English

Java:将TRUE / FALSE的所有可能组合添加到列表中

[英]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. 这是我在Java中执行的某些生成类型的一部分。 But Bool.TRUE/Bool.FALSE works sort of like normal java booleans so you can count on that. 但是Bool.TRUE / Bool.FALSE的工作方式类似于普通的Java布尔值,因此您可以依靠它。

I am trying to make a loop that will give me all possible combinations of TRUE/FALSE on: 我正在尝试创建一个循环,该循环将为我提供以下所有可能的TRUE / FALSE组合:

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: 使用Bool#values()迭代枚举的可能值:

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. 一种方法是运行02^n (不包括)之间的整数-其中n是您需要分配的变量数。

Then, you can use (x >> k) % 2 to get the value of variable number k. 然后,您可以使用(x >> k) % 2来获取变量数k的值。

This works only for having less than 64 values (using long variables). 这仅适用于少于64个值(使用long变量)。

       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. 请注意,通过将val1,val2,...切换到数组val1,val2,...可以轻松地将此方法修改为任意数量的变量(适合long )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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