Skip to content

Instantly share code, notes, and snippets.

@QuadFlask
Created May 1, 2016 03:16
Show Gist options
  • Save QuadFlask/49416913830ba4ac665e21c624d95ce4 to your computer and use it in GitHub Desktop.
Save QuadFlask/49416913830ba4ac665e21c624d95ce4 to your computer and use it in GitHub Desktop.
[CodeWars] simple finite state machine

간단한 유한 상태 머신 구현하기

My Solution

function Automaton()
{
	this.currentState = 'q1';
	this.states = [{
		'q1': 'q1',
		'q2': 'q3',
		'q3': 'q2'
	},{
		'q1': 'q2',
		'q2': 'q2',
		'q3': 'q2'
	}];
}

Automaton.prototype.readCommands = function(commands)
{
  commands.forEach(c=> 
  	this.currentState = this.states[c][this.currentState]
  );
  return this.currentState=='q2';
}

var myAutomaton = new Automaton();

// Do anything necessaryto set up your automaton's states, q1, q2, and q3.

상태맵? 함수? 를 보다 간단하게 구현하고 리듀스를 사용하는게 더 좋을듯. 리듀스할때 꼭 타입이 같아야 할거 같아서 새로 함수를 만들어야 하나 했는데 그게 아닌가봄ㅋ

Best Practice

// this class-like stuff shouldn't be necessary here
function Automaton()
{  
  // this defines transition function
   this.states = { 
     "q1": ["q1", "q2"],
     "q2": ["q3", "q2"],
     "q3": ["q2", "q2"]
   };
}

Automaton.prototype.readCommands = function(commands)
{
  // we don't even have to store current state anywhere
  return "q2" === commands.reduce(function(state, input) {
    return this.states[state][input];
  }.bind(this), "q1");
}

var myAutomaton = new Automaton();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment