对于完全不同的事物, 这是一个生成所需的字符串, 而不是其它东西的方法。 把它看成国家机器, 并让每个函数都显示一个函数。 非常动听但直截了当 。 (如果你做了很多, 您可以很容易地安排自动生成这个代码 。)
因为我们被要求使用 Java 。 这是 Java 。 ( 我用 Perl 写了相同的代码 。 我刚刚做了一个字符串的 < code>. / code > 和 < code> > chop code >, 而不是 < code> StringBuilder , 它的运行速度比 Java 版本快3x。 Odd 。 )
import java.io.*;
public class ListAllAlarmedStrings {
static StringBuilder builder;
static int length;
public static void main(String[] args) throws IOException {
length = 5;
if (args.length > 0) {
try {
length = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("Argument" + " must be an integer");
System.exit(1);
}
}
builder = new StringBuilder(length);
for (int i = 0; i < length; i++)
builder.append("O");
stateA(0, A );
stateL(0, L );
stateNone(0, O );
}
static void stateNone (int pos, char chr) {
if (length < pos + 3)
return;
builder.setCharAt(pos, chr);
//System.out.println("stateNone " + pos + " " +builder.toString());
stateA(pos + 1, A );
stateL(pos + 1, L );
stateNone(pos + 1, O );
}
static void stateL (int pos, char chr) {
if (length < pos + 3)
return;
builder.setCharAt(pos, chr);
//System.out.println("stateL " + pos + " " +builder.toString());
stateA(pos + 1, A );
stateLL(pos + 1, L );
stateNone(pos + 1, O );
}
static void stateLL (int pos, char chr) {
if (length < pos + 2)
return;
builder.setCharAt(pos, chr);
//System.out.println("stateLL " + pos + " " +builder.toString());
stateA(pos + 1, A );
stateAlarmed(pos + 1, L );
stateNone(pos + 1, O );
}
static void stateA (int pos, char chr) {
if (length < pos + 2)
return;
builder.setCharAt(pos, chr);
//System.out.println("stateA " + pos + " " +builder.toString());
stateAlarmed(pos + 1, A );
stateAL(pos + 1, L );
stateA(pos + 1, O );
}
static void stateAL (int pos, char chr) {
if (length < pos + 2)
return;
builder.setCharAt(pos, chr);
//System.out.println("stateAL " + pos + " " +builder.toString());
stateAlarmed(pos + 1, A );
stateALL(pos + 1, L );
stateA(pos + 1, O );
}
static void stateALL (int pos, char chr) {
if (length < pos + 2)
return;
builder.setCharAt(pos, chr);
//System.out.println("stateALL " + pos + " " +builder.toString());
stateAlarmed(pos + 1, A );
stateAlarmed(pos + 1, L );
stateA(pos + 1, O );
}
static void stateAlarmed (int pos, char chr) {
if (length <= pos)
return;
if (length == pos + 1) {
builder.setCharAt(pos, chr);
System.out.println(builder.toString());
return;
}
builder.setCharAt(pos, chr);
stateAlarmed(pos + 1, A );
stateAlarmed(pos + 1, L );
stateAlarmed(pos + 1, O );
}
}