# 沒有記憶的機器

`a` 代表抽掉一片花瓣，1 代表「不愛我」，2 代表「愛好」，如果有這台機器，把花丟給它，若抽掉最後一片花瓣是處於 2，那就恭喜了！

• 連續偶數個 1
• 0 與 0 之間有偶數個 1
• 10 與 01 之間有任意個 1

``````class Rule {
constructor({state, input, nextState}) {
this.state = state;
this.input = input;
this.nextState = nextState;
}

isApplicableTo(state, input) {
return this.state === state &&
this.input === input;
}
}

const REJECT = -1;

class Manual {
constructor(rules) {
this.rules = rules;
}

next_state(state, input) {
let rule = this.rules
.find(rule => rule.isApplicableTo(state, input));

return rule ? rule.nextState : REJECT;
}
}

class FA {
constructor(manual, state, acceptables) {
this.manual = manual;
this.state = state;
this.acceptables = acceptables;
}

canAccept(text) {
let manual = this.manual;
function digest(state, txt) {
if(state === REJECT || txt.length === 0) {
return state;
}
return digest(manual.next_state(state, txt[0]), txt.slice(1));
}

let state = digest(this.state, text);
return state !== -1 && this.acceptables.includes(state);
}
}

let manual = new Manual([
new Rule({
state : 1,
input : '0',
nextState : 1
}),
new Rule({
state : 1,
input : '1',
nextState : 2
}),
new Rule({
state : 2,
input : '1',
nextState : 1
}),
new Rule({
state : 2,
input : '0',
nextState : 3
}),
new Rule({
state : 3,
input : '1',
nextState : 3
}),
new Rule({
state : 3,
input : '0',
nextState : 2
})
]);

let fa = new FA(manual, 1, [1]);
console.log(fa.canAccept('1101110111101'));
``````