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

后端 未结 7 2271
野的像风
野的像风 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条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 14:00

    Here's a simple version implemented using recursion

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

提交回复
热议问题