Skip to content
Browse files

should be working nondeterministic turing machine, but missing unders…

…core library here and no internet connection
  • Loading branch information...
1 parent 5e0d019 commit e45b6b3859ee4b08c4d2e9b7c457b7dfa94dc03b @Swizec committed Nov 23, 2011
Showing with 24 additions and 18 deletions.
  1. +5 −5 machine.json
  2. +19 −13 turing.js
View
10 machine.json
@@ -1,6 +1,6 @@
[{"from": "q0", "to": "q1", "via": 1, "put": 1, "move": 1},
- {"from": "q1", "to": "q1", "via": 1, "put": 1, "move": 1},
- {"from": "q1", "to": "q2", "via": "eps", "put": 1, "move": -1},
- {"from": "q2", "to": "q2", "via": 1, "put": 1, "move": -1},
- {"from": "q2", "to": "q3", "via": "eps", "put": "eps", "move": 1},
- {"from": "q3", "to": "q4", "via": 1, "put": 0, "move": 1}]
+ {"from": "q0", "to": "q2", "via": 1, "put": 1, "move": 1},
+ {"from": "q1", "to": "q1", "via": 0, "put": 0, "move": 1},
+ {"from": "q2", "to": "q2", "via": 1, "put": 1, "move": 1},
+ {"from": "q1", "to": "q3", "via": 1, "put": 1, "move": -1},
+ {"from": "q2", "to": "q3", "via": "eps", "put": 1, "move": -1}]
View
32 turing.js
@@ -1,30 +1,36 @@
// transition format: {from: 'q1', to: 'q2', via: 'A', put: 'B', move: 1/-1}
-// spits out end word
+// spits out whether end state was reached
// basic way to run: node turing.js machine.json 111 q0 q4
// node turing.js <instructions> <word> <start> <end>
var tape = process.argv[3];
var instructions = JSON.parse(require('fs').readFileSync(process.argv[2], 'utf-8'));
var start = process.argv[4];
var stop = process.argv[5];
+var _ = require('underscore');
-var delta = function (tape, states, state, i, end) {
- if (state == end) return true;
- var cur = (tape[i]) ? states[state][tape[i]] : states[state]['eps'];
- var yes = false;
-
- if (cur) {
- if (cur.put != "eps") tape.splice(i, 1, cur.put);
- yes = delta(tape, states, cur.to, i+cur.move, end);
- }
- return yes;
+var delta = function (states, step, end) {
+ if (_.keys(step).indexOf(end) >= 0) return true;
+ var _step = {},
+ yes = _.any(_.keys(step).map(function (k) {
+ var i = step[k][0], t = step[k][1];
+ var cur = (t[i]) ? states[k][t[i]] : states[k]['eps'];
+ if (cur) {
+ if (cur.put != "eps") t.splice(i, 1, cur.put);
+ _step[cur.to] = [i+cur.move, t];
+ return true;
+ }
+ return false;
+ }));
+ return (_step.length) ? yes || delta(states, _step, end) : false;
};
var states = {};
instructions.map(function (instr) {
states[instr.from] = states[instr.from] || {};
- states[instr.from][instr.via] = instr;
+ states[instr.from][instr.via] = states[instr.from][instr.via] || [];
+ states[instr.from][instr.via].push(instr);
});
-console.log(delta(tape.split(""), states, start, 0, stop));
+console.log(delta(states, {start: [0, tape.split("")]}, stop));

0 comments on commit e45b6b3

Please sign in to comment.
Something went wrong with that request. Please try again.