Open In App

Design Turing Machine to reverse String consisting of a’s and b’s

Last Updated : 26 Oct, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite : Turing Machine

Task :
Our task is to design a Turing machine to reverse a string consisting of a’s and b’s.

Examples :

Input-1 : aabb
Output-1 : bbaa

Input-2 : abab
Output-2 : baba

Approach :
The basic idea is to read the input from Right to Left and replace Blank(B) with the alphabet and replace the alphabet with ‘X’. When we read all the a’s and b’s replace all the ‘X’ with Blank(B) and we get the required string.

Let us understand this approach by taking the example “aabb”.

  1. The first task is that we have to take our pointer to the right so that we can read our string from right to left. To do that we read all the a’s and b’s from left to right and when we get first Blank(B) we turn the pointer to left and we get the rightmost character.

  2. Now there will be two cases –
    • The character we get is ‘a’.
    • The character we get is ‘b’.


  3. In this example we get our first character as ‘b’ i.e the last character of aabb. We replace b with ‘X’ and make Blank(B). An extra Blank will automatically append at the end. Our string looks like this –


  4. Now we have to get our second character. For that, we move the pointer from right to left and move it until we get an ‘a’ or’b’ after ‘X’. In this case, we get ‘b’. Now we repeat the same task, i.e. we replace that ‘b’ with X and move the pointer from that position to right until we get a Blank(B). When we get a Blank(B) we replace it with the character we get in this case ‘b’ and a Black(B) will automatically append at the end. Our string looks like this –


  5. Now we have to get or the third character. For that, we move the pointer from right to left and move it until we get an ‘a’ or’b’ after ‘X’. In this case, we get ‘a’. Now we repeat the same task, i.e. we replace that ‘a’ with X and move the pointer from that position to right until we get a Blank(B). When we get a Blank(B) we replace it with the character we get in this case ‘a’ and a Black(B) will automatically append at the end. Our string looks like this –


  6. Similarly we get our last character which is ‘a’ and we perform the same task as describe in the above steps. Our string will look like this –


  7. Now we have seen that we have traversed all the four-character and we get the character in order “bbaa” which is reverse of “aabb” i.e. after removing all the ‘X’ we get our required string.

  8. To remove all the ‘X’ we replace all the ‘X’ with Blank(B) i.e. we get 4 Blank(B) after replacing ‘X’ which is equivalent to a single Blank(B). It means we get our final string.




Turing Machine :


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads