Search code examples
regexregular-languageautomatacomputation-theorydfa

DFA and Regular Expression


A program should not write to a connection handle while the handle is in "closed" state. At the beginning, a connection will be in "connected" state, but it can move to the "error" state when "disconnect" event is followed by "write". A "reconnect" event moves connection back into "connected" state, in which "write" operations are allowed. Multiple disconnects, reconnect and writes are redundant which means second consecutive operation has no effect.

Model it as a regular expression and DFA?

I thought of DFA as 4 states: connect, disconnect, write, error and three possible moves from them (connect, write and disconnect) but no idea of regular expression.


Solution

  • I read it slightly differently, with three states:

    1. Open
    2. Closed
    3. Error

    and three characters/transitions

    1. write
    2. disconnect
    3. reconnect

    With a DFA of DFA

    Here I've assumed that we can't leave the socket open, so only closed is an acceptance state

    We can ignore error (There's no way out of the error state because we want to fail those strings)

    Assuming we start in the open state, need to accept any number of write and reconnect transitions, then one or more disconnect transitions to disconnect

    [wr]*d+
    

    But we can also reconnect from the disconnected state. Note that the above accepts r as the first character. Our final regular expression is

    ([wr]*d+)+