我正在尝试编写一个函数,将类似“--”的输入转换为000001010011100101110和111另一个例子是“1--”->100101110111到目前为止,这是我的代码,但它只产生了一些解决方案:

static void expandPLA(char[]plaRow){
        boolean sawDontCare=false;
        for(int x = 0; x< plaRow.length; x++){
            if(plaRow[x]=='-'){
                sawDontCare=true;
                plaRow[x]='0';
                expandPLA(plaRow);
                plaRow[x]='1';
                expandPLA(plaRow);
            }
        }
        if(!sawDontCare)
            arrayList.add(plaRow);
    }

arrayList保存输出值有人知道怎么了吗?

最佳答案

我为您创建了一个示例实现,它打印了一个值列表,如上面所示当然,你可以做任何你想做的事情来代替打印来控制台:

import java.util.*;
import java.lang.*;

class Main {

    public static void expandPLA(char[] pla) {

        // How many don't cares are we handling
        int empties = 0;
        for (int i = 0; i < pla.length; i++) {
            if (pla[i] == '-') { empties++; }
        }

        // Now we know we're counting from 0 to 2^empties in binary
        for (int j = 0; j < Math.pow(2,empties); j++) {

            // For each value of j we're going to create a new string pattern
            // and fill in each don't care with the correct digit of j
            String pattern = String.copyValueOf(pla);
            String bin = Integer.toBinaryString(j);

            // Pad bin with zeros
            int pad = empties - bin.length();
            for (int z = 0; z < pad; z++) {
                bin = "0" + bin;
            }

            // For each empty spot we're going to replace a single '-' with
            // the next most significant digit
            for (int k = 0; k < empties; k++) {
                char digit = bin.charAt(k);
                pattern = pattern.replaceFirst("-", String.valueOf(digit));
            }

            // We're just going to print this out for now, but you can do
            // whatever it is you want at this point.
            System.out.println(pattern);

        }

    }

    public static void main (String[] args) throws java.lang.Exception {
        Main.expandPLA(new char [] { '1', '-', '-', '1', '-', '1', '-', '-' });
    }

}

注:我上面的算法可能会收紧很多。我懒得用0来填充二进制数,很可能有更好的方法将我的数字放入不在乎的空格,而不是字符串替换认为这是一个概念的证明,可以更节省内存和时间,但我相信这比递归更优越。

10-08 08:18