export class TuringMachine { constructor({ tape, rules, startState, acceptStates = [], rejectStates = [] }) { this.tape = tape; this.rules = rules; this.state = startState; this.acceptStates = new Set(acceptStates); this.rejectStates = new Set(rejectStates); this.iteration = 0; } step() { if (this.isHalted()) { return false; } const currentSymbol = this.tape.readHead(); const ruleKey = this.getRuleKey(this.state, currentSymbol); if (!this.rules.has(ruleKey)) { return false; } const { nextState, writeSymbol, direction } = this.rules.get(ruleKey); this.tape.writeHead(writeSymbol); if (direction === "R") { this.tape.moveRight(); } else if (direction === "L") { this.tape.moveLeft(); } this.state = nextState; this.iteration += 1; return !this.isHalted(); } canStep() { if (this.isHalted()) { return false; } const currentSymbol = this.tape.readHead(); const ruleKey = this.getRuleKey(this.state, currentSymbol); return this.rules.has(ruleKey); } getRuleKey(state, symbol) { return `${state}:${symbol}`; } isAccepting() { return this.acceptStates.has(this.state); } isRejecting() { return this.rejectStates.has(this.state); } isHalted() { return this.isAccepting() || this.isRejecting(); } getStateStatus() { return `State: ${this.state}, Step: ${this.iteration}`; } getState() { return this.state; } }