Advertisement
xladomaz

Turing Machine

Nov 23rd, 2019
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.32 KB | None | 0 0
  1. <?php
  2. //Enter your code here, enjoy!
  3.  
  4. $input_string = '1 * 1 1';
  5. $input_string_array = explode(' ', $input_string);
  6.  
  7.  
  8. $cassette = array_merge(['a0'], $input_string_array, ['a0']);
  9.  
  10.  
  11.  
  12. $position = count($input_string_array) ;
  13. $table = [
  14.     'q1' => ['', ['q2', 'a0', 'l'], ['q0', 'a0', 's']],//['q3', '1', 'r'], ['q1', 'a0', 'l']
  15.     'q2' => [['q3', '1', 'r'], ['q2', '1', 'l'], ['q2', '*', 'l']],
  16.     'q3' => [['q1', 'a0', 'l'], ['q3', '1', 'r'], ['q3', '*', 'r']]
  17. ];
  18.  
  19. $q = 'q1';
  20.  
  21. $count_iter = 0;
  22. //echo $cassette[$position] . ' ' . $q . PHP_EOL;
  23.  
  24. //print_r($table[$q][$cassette[$position]]);
  25.  
  26. while($q != 'q0') {
  27.     if($count_iter > 500)
  28.         break;
  29.     $count_iter++;
  30.     $current = $table[$q][toRow($cassette[$position])];
  31.     $cassette[$position] = $current[1];
  32.     $q = $current[0];
  33.     if($current[2] == 'l') {
  34.         $position--;
  35.     }elseif($current[2] == 'r') {
  36.         $position++;
  37.     }
  38.     if($position < 0) {
  39.         $cassette = array_merge(['a0'], $cassette);
  40.         $position = 0;
  41.     }
  42.     if($position > count($cassette))
  43.         $cassette = array_merge($cassette, ['a0']);
  44.     echo $count_iter . ') Cassette: ' . implode(' ', $cassette) . ' (' . $q . ')' . PHP_EOL;
  45. }
  46.  
  47. function toRow($name) {
  48.     $rows = ['a0' => 0, '1' => 1, '*' => 2];
  49.     return $rows[$name];
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement