I'm trying to implement Turing machine on C#. I convert word to chart array and work with array.
public TuringMachine(String word) {
word = " " + word + " ";
tapeArray = word.ToCharArray();
}
I have to detect line/string/word that ends in number 1.
So if I input 1010100101
, I get this
>1
>Word ends in 1
But if I input 10101010
, I get IndexOutOfRangeException
.
Here full code:
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;
}
}
}
Can someone explain why I get IndexOutOfRangeException
?
Sorry for bad English