среда, 13 апреля 2016 г.

JavaScript Turing Machine

All it needs are some instructions, the initial state of the tape as a list, an end state and a start state. It will return either the final tape state or false if the end state is never reached. ‘B’ is considered a blank state and the tape behaves as infinite in both directions.

function tm (I, tape, end, state, i, cell, current) {
    i = 0;
    while (state != end) {
        cell = tape[i];
        current = (cell) ? I[state][cell] : I[state].B;
        if (!current) {return false;}
        tape.splice(i, 1, current.w);
        i += current.m;
        state = current.n;
    }
    return tape;
}

// For testing purposes, run in Node.js as command:
// node turing-140.js machine-140.json 111 q5
// Instructions tape endstate.

console.log(
    tm(
           JSON.parse(
               require('fs').readFileSync(process.argv[2], 'utf-8')
           )
         , process.argv[3].split("")
         , process.argv[4]
         , "q0"
    ).join("")
);

For testing use a simple multiply program that basically turns 111 into 1110111. So this is what the algorithm’s implementation ends up looking like

{
    "q0": {"1": {"w": "B", "m": 1, "n": "q1"}},
    "q1": {"1": {"w": "1", "m": 1, "n": "q1"},
        "0": {"w": "0", "m": 1, "n": "q2"},
        "B": {"w": "0", "m": 1, "n": "q2"}},
    "q2": {"1": {"w": "1", "m": 1, "n": "q2"},
        "B": {"w": "1", "m": -1, "n": "q3"}},
    "q3": {"1": {"w": "1", "m": -1, "n": "q3"},
        "0": {"w": "0", "m": -1, "n": "q3"},
        "B": {"w": "1", "m": 1, "n": "q4"}},
    "q4": {"1": {"w": "B", "m": 1, "n": "q1"},
        "0": {"w": "0", "m": 1, "n": "q5"}}
}

There’s a smaller solution of Turing Machine in a less verbose language:

function(a,b,c,d,e){for(e=0;d<c;)with(a[d][b[e]||"B"])b[e]=w,e+=m,d=n;return b}

Комментариев нет:

Отправить комментарий