我正在尝试编写一个函数,将“---”之类的输入转换为 000,001,010,011,100,101,110 和 111。另一个示例是“1--”-> 100,101,110,111。到目前为止,这是我的代码,但它只产生了一些解决方案:
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 填充我的二进制数,并且可能有比字符串替换更好的方法将我的数字放入无关空格。将此视为一种概念证明,它可以提高内存和时间效率,但我认为它优于递归。
关于java - 将无关紧要展开为二进制数的递归方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15513184/