javascript-turing/turing.js
Christoffer Müller Madsen 212f337688 initial commit, it works
2016-09-12 19:42:05 +02:00

156 lines
2.8 KiB
JavaScript

var fs = require('fs');
var readline = require('readline');
var transitionReader = readline.createInterface({
input: fs.createReadStream('transitions')
});
var tapeReader = readline.createInterface({
input: fs.createReadStream('tape')
});
transitionReader.on('line', function(line) {
console.log(line);
var file_transitions = line.split(/[\s,]/);
if (!transitions[file_transitions[0]]) {
transitions[file_transitions[0]] = {};
}
transitions[file_transitions[0]][file_transitions[1]] = {
to:file_transitions[2],
write:file_transitions[3],
move:file_transitions[4]
};
console.log(transitions);
});
transitionReader.on('close', function() {
console.log("Done reading TRANSITIONS!");
trans_done = 1;
});
tapeReader.on('line', function(line) {
console.log("Lol");
var symbols = line;
for (var i = 0; i < symbols.length; i++) {
if (symbols[i] == " ") {
tape[i+1] = "_";
} else {
tape[i+1] = symbols[i];
}
console.log(tape);
}
});
tapeReader.on('close', function() {
console.log("Done reading TAPE!");
tape_done = 1;
});
var step_time = 10;
// TEMP SOLUTION
var trans_done = 0;
var tape_done = 0;
// END TEMP
var head_loc = 0;
var state = 0;
var tape = ["_"];
var transitions = {};
/*
var readLines = function(input, func) {
var linesToRead = '';
input.on('data', function(data) {
linesToRead += data;
var index = linesToRead.indexOf('\n');
var last = 0;
while (index > -1) {
var line = linesToRead.substring(last, index);
last = index + 1;
linesToRead = linesToRead.substring(index + 1);
func(line);
index = remaining.indexOf('\n');
}
});
input.on('end', function() {
if (linesToRead.length > 0) {
func(remaining);
}
});
}
*/
var initialiseTransitions = function(callback) {
}
var initialiseTape = function(callback) {
}
var step = function() {
console.log("Step!");
if (tape[head_loc] == undefined) {
tape[head_loc] = "_";
}
var cur_symbol = tape[head_loc];
console.log("Symbol: %s | State: %s",cur_symbol,state);
//console.log(tape[head_loc]);
var transition = transitions[state][cur_symbol];
console.log(transition);
// Write to tape
tape[head_loc] = transition.write;
// Change state
state = transition.to;
// Move head
if (transition.move == 'R') {
head_loc++;
} else if (transition.move == 'L') {
head_loc--;
}
console.log("State: %s | Head: %s",state,head_loc)
if (head_loc == -1) {
throw "head_loc error";
}
console.log("Tape %s",tape);
setTimeout(step, step_time);
}
var prestep = function() {
if (trans_done == 1 && tape_done == 1) {
console.log("Ready! Stepping!");
step();
} else {
console.log("Not ready! Waiting 100 ms...");
setTimeout(prestep, 100);
}
}
prestep();