Java: Generator of true's & false's combinations by giving the number N;

后端 未结 7 2268
野的像风
野的像风 2020-12-09 13:53

I tied to simplify the task as much as possible, so I could apply it to my algorithm.

And here is the challenge for mathematicians and programmers:

I need to

7条回答
  •  -上瘾入骨i
    2020-12-09 14:22

    Using recursion is not as easy as using the Java Integer.toBinaryString() API for generating binary strings. But the code below gives you the flexibility to generate any base representation, e.g. base 3: "000" "001" "002" "010" "011" "012"

    For base 2 (i.e. binary) strings, you call it like this:

    getBinaryStrings(2, 3);
    

    For base 3 strings, you call it like this:

    getBinaryStrings(3, 3);
    

    Here is the code:

    public static List getBinaryStrings(int base, int n){
        ArrayList result = new ArrayList<>();
        getBinaryStringsCore(base, n, "", result);
        return result;
    }
    
    private static void getBinaryStringsCore(int base, int n, String tempString, List 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);
        }
    }
    

提交回复
热议问题