summaryrefslogtreecommitdiff
path: root/turing-machine/js/turing_machine.js
diff options
context:
space:
mode:
authorElizabeth Hunt <elizabeth.hunt@simponic.xyz>2023-10-24 22:28:40 -0600
committerElizabeth Hunt <elizabeth.hunt@simponic.xyz>2023-10-24 22:28:40 -0600
commit4ce505b125950521860f0d2170409719927f3f85 (patch)
treefc5d256d0c7bc1403c648c617b4e0d17416e4877 /turing-machine/js/turing_machine.js
parentd6b885b318f68f9be19fd3dcc4d77e0f30f25ff5 (diff)
downloadsimponic.xyz-4ce505b125950521860f0d2170409719927f3f85.tar.gz
simponic.xyz-4ce505b125950521860f0d2170409719927f3f85.zip
initial turing machine
Diffstat (limited to 'turing-machine/js/turing_machine.js')
-rw-r--r--turing-machine/js/turing_machine.js82
1 files changed, 82 insertions, 0 deletions
diff --git a/turing-machine/js/turing_machine.js b/turing-machine/js/turing_machine.js
new file mode 100644
index 0000000..9c21983
--- /dev/null
+++ b/turing-machine/js/turing_machine.js
@@ -0,0 +1,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;
+ }
+}