summaryrefslogtreecommitdiff
path: root/turing-machine/js/turing_machine.js
blob: 9c2198329e18630be70bdaf6105ccf0e5d18c032 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
class TuringMachine {
  constructor(
    tape = [],
    rules = [],
    initialState = "q0",
    blankSymbol = "B",
    acceptState = "f"
  ) {
    this.tape = tape;
    this.rules = this.parseRules(rules);
    this.state = initialState;
    this.head = 0;
    this.blankSymbol = blankSymbol;
    this.acceptState = acceptState;

    this.iteration = 0;
  }

  getStateStatus() {
    return `State: ${this.state}, Step: ${this.iteration}`;
  }

  getHead() {
    return this.head;
  }

  getState() {
    return this.state;
  }

  getTapeAtCell(idx) {
    return this.tape[idx];
  }

  setTapeAtCell(idx, val) {
    this.tape[idx] = val;
  }

  isAccepting() {
    return this.state == this.acceptState;
  }

  parseRules(rules) {
    const parsedRules = {};
    for (const [currentState, readSymbol, action, newState] of rules) {
      const key = `${currentState},${readSymbol}`;
      const value = `${newState},${action}`;
      parsedRules[key] = value;
    }
    return parsedRules;
  }

  step() {
    const currentSymbol = this.tape[this.head] || this.blankSymbol;
    const key = `${this.state},${currentSymbol}`;
    if (!(key in this.rules)) {
      return false;
    }
    const rule = this.rules[key];
    const [newState, action] = rule.split(",");

    this.state = newState;

    if (action === "R") {
      this.head += 1;
    } else if (action === "L") {
      this.head -= 1;
    } else {
      this.tape[this.head] = action;
    }

    if (this.isAccepting()) {
      return false;
    }

    if (this.head >= 0 && this.head < this.tape.length) {
      this.iteration++;
      return true;
    }
    return false;
  }
}