有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

递归Java:通过给出数字N生成真与假的组合;

我尽量简化任务,以便将其应用到我的算法中

这是数学家和程序员面临的挑战:

我需要创建一个传递参数int n的方法:

public void optionality_generator(int n){
  //some kind of loops, or recursions...to make it workable
  System.out.println("current combination: ...");
}

输出应显示真和假的所有可能组合

以下是示例,其中N=1;N=2;N=3;N=4;N=5,其中x=false,0=true;请注意,空的分隔线只是为了让您更容易识别模式。希望我包括了所有可能的组合):

Combination of 1:
0
x

Combination of 2:
00
x0
0x
xx

Combination of 3:
000
X00
0X0
00X
XX0
0XX
XXX

Combination of 4:
0000

X000
0X00
00X0
000X

XX00
X0X0
X00X

0XX0
0X0X

00XX

XXX0
XX0X
X0XX
0XXX

XXXX

Combination of 5:
00000
X0000
0X000
00X00
000X0
0000X

XX000
X0X00
X00X0
X000X

X0X00
X00X0
X000X

0XX00
0X0X0
0X00X

00XX0
00X0X

000XX

XXX00
XX0X0
XX00X

X0XX0
X0X0X
X00XX

0XXX0
0XX0X

00XXX

XXXX0
XXX0X
XX0XX
X0XXX
0XXXX

XXXXX

此外,如果您看到输出,这里是我识别的模式,所有组合都对半倒置(例如,第一个组合是00000,最后一个是XXXXX,第二个是X0000,最后一个之前的一个是0XXXX等等)。也许,这种模式将有助于提高整个算法的效率,但对此并不确定。 提前谢谢你


共 (6) 个答案

  1. # 1 楼答案

    下面是一个使用递归实现的简单版本

    public void optionality_generator(int n){
        ArrayList<String> strings = generatorHelper(n); 
        for(String s : strings){
            System.out.println(s);
        }
    }
    
    private ArrayList<String> generatorHelper(int n){
        if(n == 1){
            ArrayList<String> returnVal = new ArrayList<String>();
            returnVal.add("0");
            returnVal.add("X");
            return returnVal;
        }
        ArrayList<String> trueStrings = generatorHelper(n-1);
        for(String s : trueStrings){
            s += "0";
        }
        ArrayList<String> falseStrings = generatorHelper(n-1);
        for(String s : falseStrings){
            s += "X";
        }
        trueStrings.addAll(falseStrings);
        return trueStrings;
    }
    
  2. # 2 楼答案

    使用递归不像使用Java整数那么容易。用于生成二进制字符串的toBinaryString()API。但以下代码为您提供了生成任何基本表示的灵活性,例如,基本3: "000" "001" "002" "010" "011" “012”

    对于基2(即二进制)字符串,您可以这样称呼它:

    getBinaryStrings(2, 3);
    

    对于基数为3的字符串,您可以这样称呼它:

    getBinaryStrings(3, 3);
    

    代码如下:

    public static List<String> getBinaryStrings(int base, int n){
        ArrayList<String> result = new ArrayList<>();
        getBinaryStringsCore(base, n, "", result);
        return result;
    }
    
    private static void getBinaryStringsCore(int base, int n, String tempString, List<String> result){
        if (tempString.length() == n) {
            result.add(tempString);
            return;
        }
    
        for (int i = 0; i < base; i++) {
            tempString += i;
            getBinaryStringsCore(base, n, tempString, result);
            tempString = tempString.substring(0, tempString.length() - 1);
        }
    }
    
  3. # 3 楼答案

    以下是一种仅使用Java API的基本方法:

    final int n = 3;
    for (int i = 0; i < Math.pow(2, n); i++) {
        String bin = Integer.toBinaryString(i);
        while (bin.length() < n)
            bin = "0" + bin;
        System.out.println(bin);
    }
    

    结果:

    000
    001
    010
    011
    100
    101
    110
    111
    

    当然,您可以将n设置为您喜欢的任何值。通过这个结果,您可以从字符串中选择第n个字符作为true/false

    如果只需要检查位是否为真,则不需要将其转换为字符串。这只是为了说明输出值

  4. # 4 楼答案

    只是一个线索,但想想为最多有“n”位的数字设置的位。您将看到位数是否从0变为“n”(本例中为3);这些位是000、001、010、011、100、101、110、111。您可以使用((n*n)-1)公式计算出适合于“n”位的最大数字

  5. # 5 楼答案

    这是一个测试驱动的版本:

    import static org.junit.Assert.assertEquals;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import org.junit.Test;
    
    public class OptionalityTest {
    
        @Test
        public void testOptionality0() throws Exception {
            assertEquals("[]", optionality(0).toString());
        }
    
        @Test
        public void testOptionality1() throws Exception {
            assertEquals("[0, x]", optionality(1).toString());
        }
    
        @Test
        public void testOptionality2() throws Exception {
            assertEquals("[00, x0, 0x, xx]", optionality(2).toString());
        }
    
        @Test
        public void testOptionality3() throws Exception {
            assertEquals("[000, x00, 0x0, xx0, 00x, x0x, 0xx, xxx]", optionality(3).toString());
        }
    
        private List<String> optionality(int i) {
            final ArrayList<String> list = new ArrayList<String>();
            if (i == 1) {
                list.add("0");
                list.add("x");
            }
            if (i > 1) {
                List<String> sublist = optionality(i - 1);
                for (String s : sublist) {
                    list.add("0" + s);
                    list.add("x" + s);
                }
            }
            return list;
        }
    
    }
    
  6. # 6 楼答案

    这应该能奏效

    int cols = 3;
    int rows = (int) Math.pow(2, cols);
    for (int row = 0; row < rows; row++)
        System.out.println(String.format("%" + cols + "s", 
                Integer.toBinaryString(row)).replace(' ', '0').replace('1', 'X'));
    

    输出:

    000
    00X
    0X0
    0XX
    X00
    X0X
    XX0
    XXX