14 finite state

Upload: nani10

Post on 02-Jun-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/10/2019 14 Finite State

    1/35

    Chapter 14

    The finite state control

    structure

    1 AnalogyHow are you feeling right now? Maybe you are happy or sleepy, dopey or grumpy, hungryor angry. Maybe you feel several of these at once, but for simplicity, lets assume that justone word describes your currentstate. How did you come to be in this state? Clearly yourstate is affected by things that happen to you the inputs you receive. ut input alonedoes not determine how you feel. !or e"ample, receiving a #$% on an e"am can leave youeither delighted or disappointed, depending on your e"pectations. Hence, your currentstate is really a function of two factors& your state a little while ago, and the input youhave received since then. 'n other words, your state at time t() is determined by your

    state at time t and the input you encountered between t and t().

    *he notion of state and of transition from one state to another as determined by acombination of previous state and input is the basis for a set of computational modelscalledfinite state machines+!Ms-. *he !M models in turn leads us in a very naturalway to a powerful and broadly applicable programming strategy which we will e"amine inthis chapter.

    2 IntroductionComputational models, or models of computation, are abstractions of devices that

    produce outputs +answers- from inputs +data-. !or simplicity, well assume a basic modelof a computational device as a blac/ bo" that has a single input channel and a singleoutput channel. 0ne simple physical form of a such a computational device would be ablac/ bo" with a set of buttons on the front, e"actly one of which can be pressed at anytime, and a set of lights on the top, e"actly one of which is lit at any time. 1n input value isspecified by pressing one of the buttons2 the output value is specified by the single lightthat is lit. 3e can easily thin/ of this device as producing a single output +light- in responseto a single input +button-. ut we can also thin/ of the device as being given a se4uence of

    5 6$$) 7onald !. tanat and tephen !. 3eiss

  • 8/10/2019 14 Finite State

    2/35

    Chapter )8 !inite tate Machines 9age 6

    inputs +by punching one button after another- and producing a se4uence of outputs +byone light after another being lit-. *he most recent input is often referred to as the currentinput, and the light currently lit is the currentoutput. :ote that what goes on inside thebo" can be very complicated or even random2 this simple model can be modified toaccommodate any computational tas/ we li/e. ut we are interested only in a small set ofthe possible behaviors of the bo", and we are interested only in behaviors that aredeterministic.

    *he simplest computational model is one in which the bo" computes a function of theinput value. uch a bo" will produce an output value +turn on a light- solely on the basisof the current input value +the last button pressed-. ecause the output value is determinedonly by the most recent input value, we say that the computation re4uires no memory2 thismeans that no information about previous inputs has to be stored to perform thecomputation that determines which light shall be lit. !urthermore, given a particular input,say the ith button, the output is always the same.

    3e are interested in a more comple" computational model that uses some information

    about past inputs in determining its output. Conceptually, we can imagine a device that/eeps trac/ of every input it has processed, that is, the entire input history. impler devicesmight /eep trac/ of less information, such as how many times the leftmost button waspressed, but even this information is unbounded in the sense that the number that must bestored may become arbitrarily large, and re4uire arbitrarily much storage to represent it.3ere interested in a simpler class of machines called !inite tate Machines +!M-, whichcan store only a finite amount of information, and give outputs that depend on thatinformation and the input.

    1 !inite tate Machine is a device that can be in any one of a specified finite set of statesand which can change state as a result of an input. *hus, each time an !M gets an input,we consider it to change states, although it may enter the same state it was in before.

    !inite state machines are useful for programming because they provide an alternativemodel for controlling program e"ecution. ;ecall that program control is what determineswhich program statement +or bloc/ of statements- is to be e"ecuted ne"t. *he mostcommon control structure is the default se4uential structure2 this causes the statements ofa program to be e"ecuted se4uentially, one after another, just as they appear in theprogram. *he other control structures are

    ). 1lternative selection. *his is usually embodied as an if, if...else, or switchstatement. *his performs one or more tests, and based on the result of the tests,chooses one bloc/ of code from a collection of bloc/s and e"ecutes it. *he bloc/of code may of course be empty, as it is in the false branch of the ifstatement.

    6. 'teration. *his is any loop structure2 it causes some loop body to be e"ecuted anumber of times with e"it from the loop based on a test.

  • 8/10/2019 14 Finite State

    3/35

    Chapter )8 !inite tate Machines 9age ach time an input symbol is received, the machine enters a new state,

    although the new state may be the same as the state it was in before. 1t each point, thecurrent state of the machine is determined completely by&

    ). the state it was in prior to the last input, and

    6. the value of the last input symbol.

    !ormally, a finite state machine consists of five components&

    S: a finite set of states. 1 !M is always in e"actly one of its states.

    s0: a particular state called thestart statethat the machine is in before it has seen any

    input.

    I: a finite set of input symbols

    O: a finite set of outputs.

    : the next state functionwhich maps a current state and current input to a new state.

    +"'- @

    :the output functionwhich maps the current state and the current input symbol to an

    output. +"'- @ 0

    *he machine starts out in s$ and loo/ing at the first symbol of a se4uence of inputsymbols. 't then issues the output appropriate to this statesymbol combination and goesto the appropriate ne"t state. 't then goes on to the ne"t input symbol and the processrepeats until the input se4uence is e"hausted2 the machine then stops. :ote that themachine is always in some state. 't starts out in s$and is left in some state when operation

    stops.

    9rinted % , = &

  • 8/10/2019 14 Finite State

    4/35

    Chapter )8 !inite tate Machines 9age 8

    Example: 0ur first e"ample of an !M is one that ta/es as input a se4uence of binarydigits and produces as output the same se4uence e"cept alternate ones have been changedto Aeros. *hus the input $))$)$))) becomes $)$$)$$)$. *he machines has two states s $and s), with s$being the start state. oth the input and output sets are B$,). *he ne"t

    state and output functions are shown in the tables below.

    Next state Output

    S 0

    1S

    S

    S

    0

    1

    0 01

    1

    state

    input input

    state

    S0

    S01S

    1S 0

    0 0

    1

    Figure 1

    1n alternate but e4uivalent representation for a !M is shown in !igure 6 below and iscalled astate diagram. tates are shown as circles2 the start state is indicated by the boldincoming arrow. *he ne"t state function and output functions are shown using directedarrows from one state to another. >ach arrow is labeled with one element of ' and oneelement of 0. 'f the machine is in some state s and the current input symbol is ", then wefollow the arc labeled "Dy from s to a new state and produce output y.

    S 0 1S

    1/1

    0/0

    1/0

    0/0

    Figure 2

    *he machine shown above produces a stream of output symbols that is e"actly as long asthe input stream. y allowing EnothingF to be an element of the output symbol set, we canspecify machines whose output stream is shorter than the input. !or e"ample, the machinein !igure < has a two symbol input set Ba,b, and produces outputs of Ba, b, EnothingF. 'treads in strings of as and bs and collapses substrings of as into a single a2 and substringsof bs into a single b. Hence the input string EaaaabaabbbbbabbabF will produce the output

    EababababF, and the input EaaaaaaaaaaaaaabF will produce EabF.

    9rinted % , = &

  • 8/10/2019 14 Finite State

    5/35

    Chapter )8 !inite tate Machines 9age G

    S S

    S

    0 1

    2

    a/a

    a/a

    a/nothing

    b/nothing

    b/b

    b/b

    Figure 3

    3.1 Example: the stamp machine

    Consider a simple vending machine that dispenses 6Gcent stamps, one at a time ). *he setof inputs are nic/els, dimes and 4uarters. 'f, for the sa/e of simplicity, we assume no coinreturn mechanism, there are only two outputs& one is a single stamp from the roll, the

    other is nothing2 that is, no stamp from the roll. *he machine must /eep trac/ of howmuch money has been put in so far, and if the amount is 6G cents or more, dispense onestamp and reduce the customers =credit= by 6G cents. :ote that the machine need notremember e"actly how much money has been put in it2 it must only remember theoutstanding credit. *herefore, since it has no other form of memory, it must have one statefor each possible amount of credit. *here will be one state indicating that the credit iscurrently Aero2 one state indicating a credit of G cents, plus states for )$, )G and 6$ cents.*here is no need for a state with a credit amount of 6G cents or more, because when thecredit amount reaches 6G cents the machine will produce a stamp and decrease the creditamount by 6G cents, all at once. *he list of states and possible actions is described in atable in !igure 8. *his table merges the output and ne"t state functions2 each rectangle

    contains an output +top line- and a new state +bottom line-.

    Figure 4

    ) 3ith postal rates constantly going up, its impossible to /eep this e"ample current. ojust return with us to those thrilling days of yesteryear when a first class stamp was 6Gcents.

    9rinted % , = &

  • 8/10/2019 14 Finite State

    6/35

    Chapter )8 !inite tate Machines 9age

    'n the above table, every possibility has been accounted for. 'n other words, no matterwhat state the machine is in and which input it receives, there is e"actly one output toproduce and one ne"t state. !or e"ample, suppose the machine is in the state =)$ cents=. 'fthe customer puts in a nic/el, it adds five cents to the amount put in so far and hence goesto state =)G cents= and produces the output =nothing=. 'f another nic/el is added, themachine goes to the E6$ centsF state and again produces EnothingF. 'f the customer thenadds a dime, the machine now has enough money to dispense a stamp and have G centscredit left over. Hence the machine produces the output Eone stampF and goes to the EGcentsF state. !rom any state in the stamp machine, adding a 4uarter will result in theoutput Eone stampF with no change in the credit balance. 1nd so the new state is in factthe same as the old.

    *he state diagram for the stamp machine, shown in !igure G, provides an easy way tovisualiAe what the stamp machine does. 't starts out in the initial state +credit I $ cents-.1n input can be a nic/el, a dime, or a 4uarter. 3hen the input is received the machine goesfrom the current state into a new state, following the arrow which is labeled with the typeof coin that has been inserted. ome arrows are also labeled to denote that a stamp is

    produced as output when these paths are ta/en. 'f the arrow the machine follows does notsay to output a stamp, then the output is =nothing=. :otice that new state doesnt alwaysimply different state. !or any credit balance, adding a 4uarter produces a stamp and leavesthe credit balance unchanged. *hus from any state, when the input is a 4uarter, themachine always enters the same state it was in before and dispenses a stamp.

    Figure 5

    1s it is currently specified, the stamp machine will cheat the user out of some money if heor she runs out of coins while the machine is in some state other than $. 3e could ma/ethe machine more realistic and more humane by adding another input& E' am doneF andadding four new outputs corresponding to giving change of G, )$, )G, and 6$ cents. 3e

    would then add a new arc from each state to the $ state with the input symbol being E' amdoneF, and the output being the appropriate amount of change. !or e"ample the arc fromthe )G cents state would dispense )G cents in change. *he arc from the $ state bac/ toitself would produce no output.

    9rinted % , = &

  • 8/10/2019 14 Finite State

    7/35

  • 8/10/2019 14 Finite State

    8/35

    Chapter )8 !inite tate Machines 9age K

    since we have now seen an even number of as. *he last output symbol produced by themachine just before it stops, gives the parity of the input. *he state diagram for thismachine is shown below. :otice one unusual thing about this machine. ince output isassociated with state transitions, there can be no output produced by the empty string eventhough the string of Aero as is of even length.

    S S0 1

    a/E

    a/O

    even odd

    Figure 6

    !igure J shows a !M that determines whether a binary integer is evenly divisible by 6, bythree, by both 6 and

  • 8/10/2019 14 Finite State

    9/35

    Chapter )8 !inite tate Machines 9age #

    and 1n for alphanumeric. :ote that once a string is found to contain both a letter and adigit, then it is certainly alphanumeric regardless of what else is in the string. Hence state8, which is where we go when we find a string to be alphanumeric, is what is called a sinkstate. 't is to finite state machines what a ;oach Motel is to a roach& once you get there,you can never leave.

    S

    S S S

    S

    0 1

    2

    3

    4

    L,B/An

    D,B/An

    D/N

    L/Ab

    L/Ab

    B/B L,B,D/An

    D/N

    B/B

    Figure 8

    6 Acceptor machines'n some cases, we can eliminate the need for the separate output function altogether andinstead incorporate the output into the states. hown below is a modified version of theEevenDodd aF machine from !igure ut this machine has the output symbols associatedwith the states rather than along the transitions. *he interpretation is that if the machine isin a particular state, then it produces the output associated with that state. 1nd the final

    output is the output associated with the state in which the machine stops rather than theoutput associated with the last transition. *he machine below produces the same output asdoes the machine in !igure . 1s a bonus, this machine correctly produces the output > forthe empty string.

    S S0 1

    a

    a

    even odd

    Figure 9

    *he second e"ample is derived from the !M in !igure J. 3e can determine the divisionproperty of the input simply by observing the state that the machine is in when it stopsafter having read the entire input se4uence. 'f it ends up in states 6 or 8, then the input isevenly divisible by only 62 if it ends up in state

  • 8/10/2019 14 Finite State

    10/35

    Chapter )8 !inite tate Machines 9age )$

    S S S

    S S S

    0 1 2

    3 4 5

    0

    0

    0

    0

    1

    1

    0

    0

    11

    1

    1b

    3

    2n

    2 n

    Figure 10

    3e can do the same thing with the !M in !igure K. tate $ indicates blan/s only2 state )indicates alphabetic2 state 6 indicates numeric2 and state < indicates alphanumeric. *herevised state diagrams are shown in !igures G and below. :ote that we have been able toadd a new output, e for empty, associated with s$.

    0 1

    2

    3

    4

    S

    S S

    S

    SL

    B

    D

    B,D

    L,D

    L,B,D

    e B

    Ab

    An

    N

    L

    D

    D

    L

    Figure 11

    1 special case of such a machine is one in which the output set contains only twoelements. 1ll input se4uences are thus mapped onto one or the other output symbol. 3ecan thin/ of the output symbols as the binary digits $ and ) and associate the notion ofEacceptF with ) and ErejectF with $. *hen we can thin/ of the machine as either acceptingor rejecting an input depending on whether that input causes the machine to stop in anaccepting or rejecting state. uch machines are called acceptorautomata.

    *he first three e"amples below are acceptor automata made from e"amples we have seenalready. *hese figures also show one further shorthand notation. 'nstead of writing theoutput values $ or ) in the each state, we use a double circle to indicate accepting states

    +output of )-, and a single circle to indicate rejecting states +output of $-.

    *he machine in !igure )6 accepts strings of as that are of even length and rejects stringsof odd length. :otice that this machine correctly accepts the empty string. *he machine in!igure )< accepts binary integers that are evenly divisible by 6 or by < or by both. *hemachine in !igure )8 accepts strings that are either alphabetic or numeric and rejectsstrings that are blan/ or alphanumeric.

    9rinted % , = &

  • 8/10/2019 14 Finite State

    11/35

    Chapter )8 !inite tate Machines 9age ))

    S S0 1

    a

    a

    even odd

    Figure 12

    S S S

    S S S

    0 1 2

    34 5

    0

    0

    0

    0

    1

    1

    0

    0

    11

    1

    1

    Figure 13

    0 1

    2

    3

    4

    S

    S S

    S

    S

    LB

    D

    B,D

    L,D

    L,B,D

    L

    D

    L

    D

    Figure 14

    *he machine in !igure )G might be used in the le"ical analysis phase of a compiler. 't ta/esstrings of characters and accepts those that are valid identifiers +for e"ample, names ofvariables or procedures-. *o be accepted, a string must begin with a letter +indicated bythe generic L- followed by letters and digits +7-. 3e denote by any character such asN or ? that is neither a letter nor digit. :ote that encountering any character ta/es usimmediately to the sin/ state

  • 8/10/2019 14 Finite State

    12/35

    Chapter )8 !inite tate Machines 9age )6

    S

    S

    S

    L

    D,S

    L,D

    L.D.S

    S0

    1

    2

    Figure 15

    *he !M in !igure ) reads strings of characters and accepts only those strings thatcontain a single unsigned integer, possibly preceded and followed by blan/s. !or the sa/eof simplicity, it is customary not to show the sin/ rejecting state nor the arrows leading toit. 'nstead, you can assume that if the machine is in some state s and loo/ing at input

    symbol ", and if there is no arrow labeled " leading from s, then you go to the sin/rejecting state and stay there. *hus, for e"ample, if the machine is in state $ and see theletter a, then you ne"t go a rejecting sin/ state.

    *he five states in this machine can be thought of as being associated with the five differentclasses of strings. 'n state $ we have seen nothing yet. 'f the machine stops in s $then we

    /now the input was empty. tate ) indicates that we have seen only blan/s so far2 endingthere indicates a string made up of blan/s only. tate 6 is associated with strings that haveAero or more blan/s followed by a contiguous substring of digits. 'n state < we /now thatwe have seen Aero or more leading blan/s followed by a contiguous substring of digitsfollowed by one or more blan/s. 1nd state 8 +not shown- is the sin/ state where we go ifwe encounter a character other than a digit or blan/ or if we see more than one contiguous

    string of digits. tates 6 and < are accepting2 the others are rejecting.

    Figure 16

    3e can ta/e our integer acceptor one step further by accepting a string of characters thatcontains one real number optionally preceded and followed by blan/s. *he real number canbe represented either in standard notation or in scientific notation. *he construction of thismachine is left as an e"ercise. *ry the machine on the following real numbers as well as onsome strings that do not contain valid reals.

    9rinted % , = &

  • 8/10/2019 14 Finite State

    13/35

    Chapter )8 !inite tate Machines 9age )))

    7 String Searching1nother practical use of acceptors is in string searching. tring searching problems arevery common problems, most notably in te"t editing. *he usual statement of the problemis& =determine whether string O occurs in string P.= +!or this problem string O will bereferred to as the pattern and string P as the target.- *he naive method of doing thiswould be to write a loop that goes through the target string a character at a time andchec/s to see if the pattern occurs beginning at that character. 1fter the complete patternhas been compared to the target, go to the ne"t character in the target string and startagain. *his simple algorithm, +which could be simplified somewhat by using the substring

    facility of Qava-, is implemented by the following code, which we will call algorithm 1&

    9rinted % , = &

  • 8/10/2019 14 Finite State

    14/35

    Chapter )8 !inite tate Machines 9age )8

    7.1 Naive String Search (Algorithm A)// Find the first occurrence of pattern in target,// beginning at position start.

    // Determine whether one string occurs in another string// starting at a specified point.// Does s1 match a substring of s2 starting in position pos?public boolean match(String s1, String s2, int pos){

    // pre: true// post: Returned value is true iff s1 matches a substring// of s2 starting in position pos.

    // Trivial case: not enough room in s2 for a match.if (s1.length()>s2.length()-pos) return false;

    int i;for (i=0; i

  • 8/10/2019 14 Finite State

    15/35

    Chapter )8 !inite tate Machines 9age )G

    characters of the input string, the finite state machine will read each character of the targete"actly once. Clearly, this is the better than algorithm 16. *he program corresponding tothis finite state machine would loo/ something li/e this&

    7.2 Finite State String Search (Algorithm B)var state = initialState;for (int i=0; i

  • 8/10/2019 14 Finite State

    16/35

    Chapter )8 !inite tate Machines 9age )

    still might be an occurrence of the pattern, so the machine moves to s6. :ow read a =6=.

    *his is not the ne"t character of the pattern, which is a =

  • 8/10/2019 14 Finite State

    17/35

    Chapter )8 !inite tate Machines 9age )J

    *o get a feel for the /inds of languages that cannot be accepted by acceptor automata,consider the language of algebraic e"pressions consisting of single letter variable namesand the operators (, , V and D. *he very simple machine in !igure )K accepts thislanguage. !igure )# shows a slightly more comple" machine that accepts arithmetice"pressions with one level of parenthesiAation allowed. ut no acceptor automaton canaccept arithmetic e"pressions that contain unbounded parenthesiAation.

    S S S0 1 2L

    L

    op

    Figure 18

    S S S0 1 2L

    L

    op

    S S S0 1 2L

    L

    op( ) (

    Figure 19

    *o see why this is true, lets assume the contrary. *hat is, lets assume that an acceptorautomaton M accepts the language of valid arithmetic e"pressions with no limit on thelevel of parentheses. ince M is a !M, it must have a finite number of states, say n states.

    :ow, consider the consider the e"pression +na-n. *his is a string of n left parenthesesfollowed by the letter a and followed by n right parentheses. 't is a valid arithmetice"pression and should thus be accepted by M. 'f we trace the action of M operating onthis string, we will see that M visits some state siat least twice while processing the left

    parentheses. 3e /now this must be true since M undergoes n state transitions whileprocessing the n left parentheses and hence visits n() states. ince there are only n statesin M, then one of the states, say si, must be visited at least twice.

    *his is an e"ample of the pigeon hole principle. 't derives its name from the pigeon holesused by post office wor/ers to sort mail. imply stated, if you have lots of letters to be putinto the only a few holes, then at least one of the holes must receive more than one letter.

    More formally, if you have a set of siAe n, and draw n() samples from this set +withreplacement,- then at least one of the elements of the set will be drawn at least twice. 'nthe case of a !M, processing an input of length n ta/es the machine through n() states&the start state plus the n new states that are arrived at via the n state transitions. Hence atleast one state must have been visited at least twice.

    Uiven that M visits sitwice, we can divide the string of left parentheses into three parts&

    ",y, and A. *he first substring " contains the parentheses that ta/e us from the start state s$

    9rinted % , = &

  • 8/10/2019 14 Finite State

    18/35

    Chapter )8 !inite tate Machines 9age )K

    to the first occurrence of si. 't is possible that " is empty if siis in fact s$. *hen substring y

    ta/es us from the first occurrence of sito the second occurrence of s i. *his substring must

    contain at least one symbol. 1nd the substring A simply contains the rest of the leftparentheses. 't ta/es the machine from sito sj, the state that M is in after seeing all of the

    left parentheses2 A might be empty too. :ow, consider the string "Aa-n. ince y contains at

    least one parenthesis, the string "A has fewer left parentheses than does "yA. Hence "Aa- ncontains more right parentheses than left parentheses and is invalid and should be rejected.ut " ta/es M from s$to si2 and A ta/es M from s ito sj. *hus in processing both strings,

    M is in state sjwith a-n remaining to be seen. ince the action of a !M is completely

    determined by its state and the input, M will thus do the same thing on both strings& it willeither accept both or reject both. ut thats an error2 M was supposed to accept one andreject the other. 1nd so we have arrived at a contradiction. 3e assumed that M e"istedand have shown that any M that alleges to accept the language will err by either acceptingan invalid string or rejecting a valid string. Hence our only conclusion is that theassumption that M e"ists must be false.

    'ntuitively, the wea/ness in finite state machines is that they have only a bounded amountof memory. 'f a tas/ re4uires more than that amount of memory, the !M cannot handlethe tas/. !or e"ample, matching arbitrarily nested parentheses ta/es an unbounded amountof memory and hence is beyond the capability of the !M. imilarly, while a !M canaccept strings that contain a single integer, no !M can determine the value of an arbitraryinteger.

    *his wea/ness in the power of the !M clearly limits what we can do with it. However,the basic notion of the !M can be e"tended and used as a control mechanism in morepowerful computational models.

    9 Extensions to the basic model*he basic !M model is a useful theoretical model of computation ut it is really toowea/ for most practical problems. !ortunately, the restrictions imposed by the basic !Mmodel turn out to be an artificial limit on how we use the model. 3e can easily e"tend thebasic !M model to provide a very powerful and useful control structure by allowing themachine to do arbitrary computation in each state, including giving the machine access toarbitrary data structures such as counters, arrays, lists, etc. *he !M serves as a controlstructure much li/e loops and alternative selection, and the statements inside the !Mcontrol structure, just li/e the statements inside a loop or select, are unrestricted.

    Consider, for e"ample, the problem of determining whether an algebraic e"pression is

    properly parenthesiAed. *his cannot be done in the pure !M model, because parenthesescan be nested arbitrarily deep, and when the machine has read more left parentheses than ithas states, it will necessarily become confused. ut a simple machine with one controlstate and a counter can handle this problem as follows&

    9rinted % , = &

  • 8/10/2019 14 Finite State

    19/35

    Chapter )8 !inite tate Machines 9age )#

    '(' and counter0 / +1

    ')' and counter > 0 / -1

    ')' and counter = 0

    fail

    Parenthesis checker. Accept if, at end of string, theautomaton is in the final state and the counter = 0.

    s0

    *he initial state of the machine is s$, with the counter initialiAed to $. 1s each left or right

    parenthesis is encountered in an input string, the ne"t state is chosen based both on thepresent state and the value of the counter. 3hen in state s$, if a + is read, the counter is

    incremented2 if a - is read, the counter is decremented. 'f the value of the counter is ever$ and a - is read, the string is not wellformed and the machine enters the fail state. 1ndif the counter is not e4ual to $ when the string is processed, there were more leftparentheses than right ones. :ote that both acceptance and the ne"t state function +and ingeneral, the output function as well- use the value of the registers in determining what todo ne"t.

    1 te"t editor on a computer provides another illustration of the finite state model. *heprincipal input to a te"t editor is /eystro/es, but the same /eystro/es can mean entirelydifferent things to the te"t editor, depending on the state of the software. Mostcommonly, /eystro/es are te"t to be inserted into the document, but, they may represent

    the name of the file under which the document is to be stored, or a character se4uence tobe searched for within the document, or instructions on how the document is to beformatted for printing. *hus, the te"t editor can be considered to have many states, and itsreaction to a se4uence of /eystro/es is dependent on which state it is in.

    *he userinterface for the WC7 9ascal ystem for the 1pple '' computer has three states&system, editor, and filer. 3hat the interface does in response to a users input depends bothon the input and on the state. !or e"ample, typing the character EeF in system state causesthe system to go to the editor state. 0nce in the editor, typing an EeF adds that characterto the file currently being edited. 1nd typing an EeF in the filer state produces a e"tendedlisting of the files on the current volume.

    1 program s/eleton for using a general !M control structure is given below. Here, the!M has been implemented using the Qava switch statement, and the end of input isindicated by a sentinel. :ote that the statements inside the case statement +indicated as=process inputymbol in state si=- are arbitrary statements, including possibly compoundstatements, or even another finite state machine construct. *he ne"t state function is afunction not only of the state si and the input symbol, but also the other parts of the state the values of registers, counters, arrays, etc.

    9rinted % , = &

  • 8/10/2019 14 Finite State

    20/35

    Chapter )8 !inite tate Machines 9age 6$

    var state = startState;

    while (true){

    get the next input symbol

    // inv: all symbols preceding the current input have been processed// in the correct state, and the current state reflects the

    // input history.

    // Stop FSM at end of input.if (input symbol == sentinel) break;

    switch (state){case s0: process input symbol in state s0;

    state = stateTransition(state, input symbol);break;

    case s1: process input symbol in state s1;state = stateTransition(state, input symbol);break;

    ...

    case sn: process input symbol in state sn;state = stateTransition(state, input symbol);break;

    }}

    1s an e"ample of the application of this control mechanism, consider a more realisticversion of the integer acceptor machine shown previously in !igure ). 'nstead of justaccepting or rejecting the input, we also want to determine the value of the integer if thestring is valid. 'n particular, we want to read an input string and first, determine if it isempty +contains no characters-, blan/ +contains only blan/s-, valid +contains a single

    unsigned integer-, or invalid +anything other than empty, blan/ or valid-. 1nd second, if thestring contains a valid integer, determine its value. 3e will ignore for now the possibleproblem of the integer being too large.

    'nteger ;eader ) below shows the traditional way of approaching this problem. 't is asieve algorithm& a series of tests. 1s the input passes each test, it goes on to the ne"t. 'f itfails a test, the algorithm stops. *he first test determines if the line is empty. 'f it is nonempty, the leading blan/s are stripped off. 'f nothing remains after blan/ stripping, thenthe string must have been blan/. 'f the string is nonblan/, then trailing blan/s arestripped. *he remaining characters are then tested to see if they are all digits. 1nd if theyare, then the value is accumulated. *o convert a character digit to its integer counterpart,we first cast the character to an integer and then subtract the integer version of $. Hence

    ((int)'3')-(int)'0'has the integer value

  • 8/10/2019 14 Finite State

    21/35

    Chapter )8 !inite tate Machines 9age 6)

    over the input and while it is longer than its predecessor, it is easy to write, understand andmodify.

    9.1 Integer Reader 1public static String stripLeadingBlanks(String s){

    // pre: true// post: Returned value is s with leading blanks removed.while (s.length()>0 && s.charAt(0)==' ') // SC eval

    s=s.substring(1);return s;

    }public static String stripTrailingBlank(String s){

    // pre: s contains a non-blank character// post: Returned value is s with trailing blanks removed.while (s.charAt(s.length()-1)==' ')

    s=s.substring(0,s.length()-1);return s;

    }

    public static String reader1(String s){

    // pre: true// post: Returned String gives string type and, if valid,// its value.String res=s;// See if string is empty.if (s.length()==0) return "|"+res+"|"+" is empty";

    // String is nonempty; strip leading blankss=stripLeadingBlanks(s);if (s.length()==0) return "|"+res+"|"+" is all blank";

    // String is not all blank; strip trailing blankss=stripTrailingBlank(s);

    // Check for all digits and accumulate valueint value=0;for (int i=0;i

  • 8/10/2019 14 Finite State

    22/35

    Chapter )8 !inite tate Machines 9age 66

    9.2 Integer Reader 2public static String reader2(String s){

    // pre: true// post: Returned String gives string type and, if valid,

    // its value.String res=s;int state=0; // State of FSM.int i=0; // String index.int value=0; //char c;while (i'b' blank// digit->'d'// something else->'s'if (s.charAt(i)==' ') c='b';else

    if (s.charAt(i)>='0' && s.charAt(i)

  • 8/10/2019 14 Finite State

    23/35

    Chapter )8 !inite tate Machines 9age 6ncodingruns of length two would produce no compression2 encoding singletons would actuallyma/e the resulting string longer.

    *o do the compression re4uires that we /eep trac/ of two things& the character seen mostrecently and the number of consecutive occurrences of that character. *he former can bedone with a !M since there are only three characters2 /eeping trac/ of the count,however, is beyond what a !M can do and is handled as an e"tension. *he procedures tocompress a string and to display the compressed string are shown below.

    public static String output(int count, char c){

    // Compress a homogeneous string of characters.// if count = 1, return c.

    // if count is 2, return cc// if count is 3 or more, return compressed form: count+c

    // pre count >= 1

    if (count == 1)return String.valueOf(c);

    elseif (count == 2)

    return String.valueOf(c)+String.valueOf(c);else

    return count+String.valueOf(c);}

    9rinted % , = &

  • 8/10/2019 14 Finite State

    27/35

    Chapter )8 !inite tate Machines 9age 6J

    public static String compress(String s){

    // Compress s by encoding runs of length 3 or more.// FSM states: 's' for start.// 'a' seeing a's.// 'b' seeing b's// 'c' seeing c'schar state = 's'; // FSM state.

    int count=1; // Current run length.String outString = ""; // String to be returned.

    for (int i=0;i

  • 8/10/2019 14 Finite State

    28/35

    Chapter )8 !inite tate Machines 9age 6K

    nearly identical. *he start state can be eliminated by ma/ing the initial state the firstcharacter of the se4uence +thus changing the range of the for loop-, and the separate casesfor the remaining states can be combined into one, eliminating the redundancies and givingthe following code.

    public static String compress(String s){// Compress s by encoding runs of length 3 or more.

    // pre: true// post: Returned value is compressed version of s.

    if (s.length()==0) return ""; // Handle empty string.

    char state = s.charAt(0); // Initialize state.int count=1; // Current run length.String outString = ""; // String to be returned.

    for (int i=1;i

  • 8/10/2019 14 Finite State

    29/35

    Chapter )8 !inite tate Machines 9age 6#

    11Exercises). 7raw the statetransition diagram for the following finite state machine and describe in

    >nglish what it does.

    et of input symbols I Ba,N

    et of output symbols I Ba,$,),6

    et of states I Bs$,s),s6

    'nitial state I s$

    output function !&

    state transition function U&

    3hat will the machine output if the input is&

    i- aaa

    ii- aaaaaaaN

    iii- aaNaaaaNaNN

    9rinted % , = &

  • 8/10/2019 14 Finite State

    30/35

    Chapter )8 !inite tate Machines 9age

  • 8/10/2019 14 Finite State

    31/35

    Chapter )8 !inite tate Machines 9age

  • 8/10/2019 14 Finite State

    32/35

  • 8/10/2019 14 Finite State

    33/35

    Chapter )8 !inite tate Machines 9age

  • 8/10/2019 14 Finite State

    34/35

    Chapter )8 !inite tate Machines 9age

  • 8/10/2019 14 Finite State

    35/35