Reputation: 45
I decided for practice that I would create a binary counter simulating the methodology of a Turing Machine. To be specific, I plan to emulate the first example from this: (https://www.cl.cam.ac.uk/projects/raspberrypi/tutorials/turing-machine/four.html) Then I will go farther to create more for my machine!
My adaption to this example is that I wish to have a set number to count up to, then stop - instead of incrementing 1 at a time.
I am using switch cases because I haven't used them in awhile, earlier, I had the same (adapted) code for if-else blocks.
The issue I'm having at the moment is that my counter doesn't seem to go past 2 advances on the "tape." Below shows that it possibly gets stuck somewhere. I suspect it is here:
case 2:
switch (symbol) {
case ' ':
s[i] = ' ';
state = 0;
i++;
break; // here?
Would it be wiser to put an increment function in this class and call that in the while (c<8)
to increment by one as the example above shows? But wouldn't that need to call for static variables? which later, when I create more operations for my machine, would create issues, yes?
public class TuringMachineSimulations {
private static void print(char[] s) {
for (int i = 0; i < s.length; i++) {
System.out.print(s[i] + "_");
}
System.out.println();
}
public static void main(String[] args) {
int n = 8; // number to count up to in binary
int c = 0; // counter
int i = 0; // index counter within 'string'
int state = 0; // state control
char symbol = ' '; // what symbol is currently being read - starting is blank
char[] s = new char[4]; // 4 bits needed to hold the integer "8" in binary
while (c < 8) {
switch (state) {
case 0:
switch (symbol) {
case ' ':
s[i] = ' ';
state = 1;
i++;
break;
case '0':
s[i] = '0';
state = 0;
i--;
break;
case '1':
s[i] = '1';
state = 0;
i--;
break;
default:
break;
}
case 1:
switch (symbol) {
case ' ':
s[i] = '1';
state = 2;
i--;
break;
case '0':
s[i] = '1';
state = 2;
i++;
break;
case '1':
s[i] = '0';
state = 1;
i++;
break;
default:
break;
}
case 2:
switch (symbol) {
case ' ':
s[i] = ' ';
state = 0;
i++;
break;
case '0':
s[i] = '0';
state = 1;
i--;
break;
case '1':
s[i] = '1';
state = 1;
i--;
break;
default:
break;
}
}
symbol = s[i];
print(s);
c++;
}
}
}
P.S. I hope to get it such that the least significant bit is the first bit.
Upvotes: 0
Views: 1750
Reputation: 27976
It looks to me as though you are assuming that each step will involve an increment of the binary number. You are running your 'steps' only 8 times. But many of those steps don't involve changing the 'tape' at all - in states 0 and 2 the 'head' is moved and the state is changed but there are no changes to the tape.
If you know the final state of 's' that you want (presumably "1000") then the easiest thing would be to replace while (c < 8)
with while (!String.valueOf(s).equals("1000"))
.
Upvotes: 0