确定性图灵机,及 3-state Busy Beaver 模拟。

确定性图灵机

https://en.wikipedia.org/wiki/Turing_machine

模拟代码

// 磁带初始状态
// 共 11 个
const TAPE = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

// 磁头初始位置
// 因为理想状态,左右两边都有无限的磁带,所以初始位置定在中心
// 左右各有 5 个位置
let head = 5

// 定义移动的操作项
const MOVE_TAPE = {
  R: () => (head = head + 1),
  L: () => (head = head - 1)
}

// 状态枚举
const STATES = {
  A: 'A',
  B: 'B',
  C: 'C',
  HALT: 'HALT'
}

// 状态表格
const STATES_TABLE = {
  '0A': {
    write: () => (TAPE[head] = 1),
    move: () => MOVE_TAPE.R(),
    next: () => STATES.B
  },
  '1A': {
    write: () => (TAPE[head] = 1),
    move: () => MOVE_TAPE.L(),
    next: () => STATES.C
  },
  '0B': {
    write: () => (TAPE[head] = 1),
    move: () => MOVE_TAPE.L(),
    next: () => STATES.A
  },
  '1B': {
    write: () => (TAPE[head] = 1),
    move: () => MOVE_TAPE.R(),
    next: () => STATES.B
  },
  '0C': {
    write: () => (TAPE[head] = 1),
    move: () => MOVE_TAPE.L(),
    next: () => STATES.B
  },
  '1C': {
    write: () => (TAPE[head] = 1),
    move: () => MOVE_TAPE.R(),
    next: () => STATES.HALT
  }
}

// 初始状态
let currentState = STATES.A

// 没有 HALT 之前,一直执行
while (currentState !== STATES.HALT) {
  // 打印内容
  printHeadPosition()
  printTape()

  // 当前磁带的符号
  // 是否是 0 或 1
  const tape = TAPE[head]

  // 通过磁带符号和当前状态,从表格中获取需要执行的操作
  const action = STATES_TABLE[`${tape}${currentState}`]

  // 操作磁带符号
  action.write()
  // 操作磁头
  action.move()
  // 切换到下一个状态
  currentState = action.next()
}

console.log('HALT!')

// 打印磁头位置
function printHeadPosition () {
  console.log(new Array(head).join('  ') + '  !')
}

// 打印磁带状态
function printTape () {
  console.log(TAPE.join(' ') + `  action: ${TAPE[head]}${currentState}`)
}

模拟结果

          !
0 0 0 0 0 0 0 0 0 0 0  action: 0A
            !
0 0 0 0 0 1 0 0 0 0 0  action: 0B
          !
0 0 0 0 0 1 1 0 0 0 0  action: 1A
        !
0 0 0 0 0 1 1 0 0 0 0  action: 0C
      !
0 0 0 0 1 1 1 0 0 0 0  action: 0B
    !
0 0 0 1 1 1 1 0 0 0 0  action: 0A
      !
0 0 1 1 1 1 1 0 0 0 0  action: 1B
        !
0 0 1 1 1 1 1 0 0 0 0  action: 1B
          !
0 0 1 1 1 1 1 0 0 0 0  action: 1B
            !
0 0 1 1 1 1 1 0 0 0 0  action: 1B
              !
0 0 1 1 1 1 1 0 0 0 0  action: 0B
            !
0 0 1 1 1 1 1 1 0 0 0  action: 1A
          !
0 0 1 1 1 1 1 1 0 0 0  action: 1C
HALT!