Skip to content

Instantly share code, notes, and snippets.

@ikr7
Created October 17, 2015 08:44
Show Gist options
  • Save ikr7/e8ee7d1a4625a630defc to your computer and use it in GitHub Desktop.
Save ikr7/e8ee7d1a4625a630defc to your computer and use it in GitHub Desktop.
決定性有限オートマトン(っぽいの)
'use strict';
let DFA = class {
constructor () {
this.states = [];
this.cursor = null;
this.acceptedState = null;
}
addState (state) {
if (this.states.length === 0) {
this.cursor = state;
}
if (state.acceptedState) {
this.acceptedState = state;
}
this.states.push(state);
}
read (string) {
for (let character of string) {
for (let rule of this.cursor.rules) {
if (character === rule.character) {
this.cursor = rule.destination;
}
}
}
}
get accepting () {
return this.cursor === this.acceptedState;
}
}
let State = class {
constructor (acceptedState) {
this.rules = [];
this.usedCharacters = [];
this.acceptedState = acceptedState;
}
addRule (rule) {
if (this.usedCharacters.indexOf(rule.character) !== -1) {
throw new Error('決定性がないぞ〜(^^)');
}
this.rules.push(rule);
this.usedCharacters.push(rule.character);
}
}
let Rule = class {
constructor (character, destination) {
this.character = character;
this.destination = destination;
}
}
let dfa = new DFA();
let state1 = new State();
let state2 = new State();
let state3 = new State(true);
state1.addRule(new Rule('b', state1));
state1.addRule(new Rule('a', state2));
state2.addRule(new Rule('a', state2));
state2.addRule(new Rule('b', state3));
state3.addRule(new Rule('a', state3));
state3.addRule(new Rule('b', state3));
dfa.addState(state1);
dfa.addState(state2);
dfa.addState(state3);
dfa.read('bbbbab');
console.log(dfa.accepting);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment