我正在尝试在 C# 上实现图灵机。我将单词转换为图表数组并使用数组。
public TuringMachine(String word) {
word = " " + word + " ";
tapeArray = word.ToCharArray();
}
我必须检测以数字 1 结尾的行/字符串/单词。所以如果我输入1010100101
,我会得到这个
>1
>Word ends in 1
但如果我输入10101010
,我得到IndexOutOfRangeException
。
这里完整的代码:
public class TuringMachine {
char[] tapeArray;
int N;
char a0 = ' ';
int i = 1;
public TuringMachine(String word) {
word = " " + word + " ";
tapeArray = word.ToCharArray();
N = tapeArray.Length;
State1();
}
public void State1() {
if (tapeArray[i] == '1') {
tapeArray[i] = '1';
i = i + 1;
State1();
}
if(tapeArray[i] == '0') {
tapeArray[i] = '0';
i = i + 1;
State1();
}
if (tapeArray[i] == a0) {
tapeArray[i] = a0;
i = i - 1;
State2();
}
}
public void State2() {
if (tapeArray[i] == '1') {
tapeArray[i] = a0;
i = i - 1;
State3();
}
if (tapeArray[i] == '0') {
tapeArray[i] = a0;
i = i - 1;
State4();
}
}
public void State3() {
if (tapeArray[i] == '1') {
tapeArray[i] = a0;
i = i - 1;
State3();
}
if (tapeArray[i] == '0') {
tapeArray[i] = a0;
i = i - 1;
State3();
}
if (tapeArray[i] == a0) {
tapeArray[i] = '1';
}
}
public void State4() {
if (tapeArray[i] == '1') {
tapeArray[i] = a0;
i = i - 1;
State4();
}
if (tapeArray[i] == '0') {
tapeArray[i] = a0;
i = i - 1;
State4();
}
if (tapeArray[i] == a0) {
tapeArray[i] = '0';
i = 1;
}
}
}
有人可以解释我为什么得到IndexOutOfRangeException
吗?
对不起英语不好