diff options
author | Elizabeth (Lizzy) Hunt <elizabeth.hunt@simponic.xyz> | 2023-11-17 12:13:30 -0700 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-11-17 12:13:30 -0700 |
commit | eaca9073ebf8a438ec8474f15171a62082fa141b (patch) | |
tree | 371b06e288a85c14fccd785008c7abfe586a6471 /godel/js/turing_machine.js | |
parent | 1aefa0f9b1da1c7bb99f7605c334eaf691ba2fda (diff) | |
parent | 57a4d439847bf3d63513b2443dfdf1eca5ecbb02 (diff) | |
download | simponic.xyz-eaca9073ebf8a438ec8474f15171a62082fa141b.tar.gz simponic.xyz-eaca9073ebf8a438ec8474f15171a62082fa141b.zip |
Merge pull request #3 from Simponic/godel
L-Program and Godel Numbers
Diffstat (limited to 'godel/js/turing_machine.js')
-rw-r--r-- | godel/js/turing_machine.js | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/godel/js/turing_machine.js b/godel/js/turing_machine.js new file mode 100644 index 0000000..a61b43a --- /dev/null +++ b/godel/js/turing_machine.js @@ -0,0 +1,72 @@ +class TuringMachine { + constructor(tape = [], rules = [], initialState = "q0", acceptState = "f") { + this.tape = tape; + this.rules = this.parseRules(rules); + this.state = initialState; + this.head = 0; + 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]; + 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; + this.iteration++; + + if (action === "R") { + this.head += 1; + } else if (action === "L") { + this.head -= 1; + } else { + this.tape[this.head] = action; + } + + if (this.isAccepting()) { + return false; + } + + return this.head >= 0 && this.head < this.tape.length; + } +} |