<p>What kind of programming problems are state machines most suited for?</p>

<p>I have read about parsers being implemented using state machines, but would like to find out about problems that scream out to be implemented as a state machine.</p>

[{'answer_id': 40604, 'author': 'user4315', 'author_id': 4315, 'author_profile': 'https://Stackoverflow.com/users/4315', 'pm_score': 2, 'selected': False, 'text': "<p>Stateful protocols such as TCP are often represented as state machines. However it's rare that you should want to implement anything as a state machine proper. Usually you will use a corruption of one, i.e. have it carrying out a repeated action while sitting in one state, logging data while it transitions, or exchanging data while remaining in one state.</p>\n"}, {'answer_id': 40607, 'author': 'Nir', 'author_id': 3509, 'author_profile': 'https://Stackoverflow.com/users/3509', 'pm_score': 1, 'selected': False, 'text': '<p>Workflow (see WF in .net 3.0)</p>\n'}, {'answer_id': 40609, 'author': 'Brian Stewart', 'author_id': 3114, 'author_profile': 'https://Stackoverflow.com/users/3114', 'pm_score': 1, 'selected': False, 'text': '<p>They have many uses, parsers being a notable one. I have personally used simplified state machines to implement complex multi-step task dialogs in applications. </p>\n'}, {'answer_id': 40611, 'author': 'nsanders', 'author_id': 1244, 'author_profile': 'https://Stackoverflow.com/users/1244', 'pm_score': 1, 'selected': False, 'text': '<p>A parser example.  I recently wrote a parser that takes a binary stream from another program.  The meaning of the current element parsed indicates the size/meaning of the next elements.  There are a (small) finite number of elements possible.  Hence a state machine.</p>\n'}, {'answer_id': 40615, 'author': 'Jordi Bunster', 'author_id': 4272, 'author_profile': 'https://Stackoverflow.com/users/4272', 'pm_score': 1, 'selected': False, 'text': "<p>They're great for modelling things that change status, and have logic that triggers on each transition.</p>\n\n<p>I'd use finite state machines for tracking packages by mail, or to keep track of the different stata of a user during the registration process, for example.</p>\n\n<p>As the number of possible status values goes up, the number of transitions explodes. State machines help a lot in that case.</p>\n"}, {'answer_id': 40618, 'author': 'chakrit', 'author_id': 3055, 'author_profile': 'https://Stackoverflow.com/users/3055', 'pm_score': 0, 'selected': False, 'text': '<p>Things that comes to mind are:</p>\n\n<blockquote>\n  <ul>\n  <li>Robot/Machine manipulation... those robot arms in factories</li>\n  <li>Simulation Games, (SimCity, Racing Game etc..)</li>\n  </ul>\n</blockquote>\n\n<p>Generalizing: When you have a string of inputs that when interacting with anyone of them, requires the knowledge of the previous inputs or in other words, when processing of any single input requires the knowledge of previous inputs. (that is, it needs to have "states")</p>\n\n<p>Not much that I know of that isn\'t reducible to a parsing problem though.</p>\n'}, {'answer_id': 40620, 'author': 'Ben', 'author_id': 3786, 'author_profile': 'https://Stackoverflow.com/users/3786', 'pm_score': 2, 'selected': False, 'text': '<p>AI in games is very often implemented using State Machines. \nHelps create discrete logic that is much easier to build and test.</p>\n'}, {'answer_id': 40621, 'author': 'caramelcarrot', 'author_id': 3877, 'author_profile': 'https://Stackoverflow.com/users/3877', 'pm_score': 2, 'selected': False, 'text': '<p>Objects in games are often represented as state machines. An AI character might be:</p>\n\n<ul>\n<li>Guarding</li>\n<li>Aggressive</li>\n<li>Patroling</li>\n<li>Asleep</li>\n</ul>\n\n<p>So you can see these might model some simple but effective states. Of course you could probably make a more complex continuous system.</p>\n\n<p>Another example would be a process such as making a purchase on Google Checkout. Google gives a number of states for Financial and Order, and then informs you of transistions such as the credit card clearing or getting rejected, and allows you to inform it that the order has been shipped.</p>\n'}, {'answer_id': 40628, 'author': '1729', 'author_id': 4319, 'author_profile': 'https://Stackoverflow.com/users/4319', 'pm_score': 2, 'selected': False, 'text': '<p>Regular expression matching, Parsing, Flow control in a complex system.</p>\n\n<p>Regular expressions are a simple form of state machine, specifically finite automata. They have a natural represenation as such, although it is possible to implement them using mutually recursive functions.</p>\n\n<p>State machines when implemented well, will be very efficient.</p>\n\n<p>There is an excellent state machine compiler for a number of target languages, if you want to make a readable state machine.</p>\n\n<p><a href="http://research.cs.queensu.ca/~thurston/ragel/" rel="nofollow noreferrer">http://research.cs.queensu.ca/~thurston/ragel/</a></p>\n\n<p>It also allows you to avoid the dreaded \'goto\'.</p>\n'}, {'answer_id': 40638, 'author': 'Hoffmann', 'author_id': 3485, 'author_profile': 'https://Stackoverflow.com/users/3485', 'pm_score': 1, 'selected': False, 'text': '<p>Just as a side note, you can implement state machines with proper tail calls like I explained in the <a href="https://stackoverflow.com/questions/33923/tail-recursion#34540">tail recursion</a> question.</p>\n\n<p>In that exemple each room in the game is considered one state.</p>\n\n<p>Also, Hardware design with VHDL (and other logic synthesis languages) uses state machines everywhere to describe hardware.</p>\n'}, {'answer_id': 40645, 'author': 'Adam Davis', 'author_id': 2915, 'author_profile': 'https://Stackoverflow.com/users/2915', 'pm_score': 3, 'selected': False, 'text': '<p>A good resource is this free <a href="http://www.xcprod.com/titan/state_machine_ebook.html" rel="noreferrer">State Machine EBook</a>.  My own quick answer is below.</p>\n\n<p>When your logic must contain information about what happened the last time it was run, it must contain state.</p>\n\n<p>So a state machine is simply any code that remembers (or acts on) information that can only be gained by understanding what happened before.</p>\n\n<p>For instance, I have a cellular modem that my program must use.  It has to perform the following steps in order:</p>\n\n<ol>\n<li>reset the modem</li>\n<li>initiate communications with the modem</li>\n<li>wait for the signal strength to indicate a good connection with a tower</li>\n<li>...</li>\n</ol>\n\n<p>Now I could block the main program and simply go through all these steps in order, waiting for each to run, but I want to give my user feedback and perform other operations at the same time.  So I implement this as a state machine inside a function, and run this function 100 times a second.</p>\n\n<pre><code>enum states{reset,initsend, initresponse, waitonsignal,dial,ppp,...}\nmodemfunction()\n{\n  static currentstate\n\n  switch(currentstate)\n  {\n  case reset:\n    Do reset\n    if reset was successful, nextstate=init else nextstate = reset\n    break\n  case initsend\n    send "ATD"\n    nextstate = initresponse \n    break\n  ...\n  }\ncurrentstate=nextstate\n}\n</code></pre>\n\n<p>More complex state machines implement protocols.  For instance a ECU diagnostics protocol I used can only send 8 byte packets, but sometimes I need to send bigger packets.  The ECU is slow, so I need to wait for a response.  Ideally when I send a message I use one function and then I don\'t care what happens, but somewhere my program must monitor the line and send and respond to these messages, breaking them up into smaller pieces and reassembling the pieces of received messages into the final message.</p>\n'}, {'answer_id': 40646, 'author': 'Adam Hollidge', 'author_id': 4069, 'author_profile': 'https://Stackoverflow.com/users/4069', 'pm_score': 0, 'selected': False, 'text': '<p>If you need a simple stochastic process, you might use a Markov chain, which can be represented as a state machine (given the current state, at the next step the chain will be in state X with a certain probability).</p>\n'}, {'answer_id': 40654, 'author': 'Eric Z Beard', 'author_id': 1219, 'author_profile': 'https://Stackoverflow.com/users/1219', 'pm_score': 1, 'selected': False, 'text': '<p>Any workflow application, especially with asynchronous activities.  You have an item in the workflow in a certain state, and the state machine knows how to react to external events by placing the item in a different state, at which point some other activity occurs.  </p>\n'}, {'answer_id': 40747, 'author': 'mweerden', 'author_id': 4285, 'author_profile': 'https://Stackoverflow.com/users/4285', 'pm_score': 5, 'selected': True, 'text': "<p>The easiest answer is probably that they are suited for practically any problem. Don't forget that a computer itself is also a state machine.</p>\n\n<p>Regardless of that, state machines are typically used for problems where there is some stream of input and the activity that needs to be done at a given moment depends the last elements seen in that stream at that point.</p>\n\n<p>Examples of this stream of input: some text file in the case of parsing, a string for regular expressions, events such as <code>player entered room</code> for game AI, etc.</p>\n\n<p>Examples of activities: be ready to read a number (after another number followed by a <code>+</code> have appear in the input in a parser for a calculator), turn around (after player approached and then sneezed), perform jumping kick (after player pressed left, left, right, up, up).</p>\n"}, {'answer_id': 63165, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>The concept of state is very useful for applications  to "remember" the current context of your system and react properly when a new piece of information arrives. Any non trivial application has that notion embedded in the code thru variables and conditionals.</p>\n\n<p>So if your application has to react differently every time it receives a new piece of information  because of the context you are in, you could model your system with with a state machines. An example would be how to interpret the keys on a calculator, which depends on what your are processing at that point in time. </p>\n\n<p>On the contrary, if your computation does not depend of the context but solely on the input (like a function adding two numbers), you will not need an state machine (or better said, you will have a state machine with zero states)</p>\n\n<p>Some people design the whole application in terms of state machines since they capture the essential things to keep in mind in your project and then use some procedure or autocoders to make them executable. It takes some paradigm chance to program in this way, but I found it very effective.</p>\n'}]
['https://Stackoverflow.com/questions/40602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1583/']