Finite State Machine

From Progzoo

(Difference between revisions)
(Even Binary Numbers - Absracted)
(Even Binary Numbers - Abtsracted)
Line 86: Line 86:
 
       String c = s.substring(i,i+1);
 
       String c = s.substring(i,i+1);
 
       state = d.get(state).get(c);
 
       state = d.get(state).get(c);
 +
      i++;
 +
    }
 +
    return state==States.A;
 +
  }
 +
}
 +
]]></prog>
 +
</question>
 +
 +
==Divisible by Three (decimal)==
 +
 +
<question className='Div3'>
 +
<prog><![CDATA[
 +
 +
public class Div3 {
 +
 +
  public static void main(String[] args) {
 +
    String [] ls = {"10", "111", "01","123"};
 +
    for (String s : ls)
 +
      System.out.printf("%10s, %s\n", s,sm(s));
 +
  }
 +
  public enum States {FAIL,A,B,C};
 +
  public static boolean sm(String s)
 +
  {
 +
    States state = States.A;
 +
    int i=0;
 +
    while (i<s.length() &&
 +
        state!=States.FAIL)
 +
    {
 +
      char c = s.charAt(i);
 +
      switch (state){
 +
      case A:
 +
        if (c=='0' || c=='3' || c=='6' || c=='9')
 +
          state = States.A;
 +
        else if (c=='1'||c=='4'||c=='7')
 +
          state = States.B;
 +
        else if (c=='2'||c=='5'||c=='8')
 +
          state = States.C;
 +
        break;
 +
      case B:
 +
        if (c=='0' || c=='3' || c=='6' || c=='9')
 +
          state = States.B;
 +
        else if (c=='1'||c=='4'||c=='7')
 +
          state = States.C;
 +
        else if (c=='2'||c=='5'||c=='8')
 +
          state = States.A;
 +
        break;
 +
      case C:
 +
        if (c=='0' || c=='3' || c=='6' || c=='9')
 +
          state = States.C;
 +
        else if (c=='1'||c=='4'||c=='7')
 +
          state = States.A;
 +
        else if (c=='2'||c=='5'||c=='8')
 +
          state = States.B;
 +
        break;
 +
      }
 
       i++;
 
       i++;
 
     }
 
     }

Revision as of 21:10, 16 February 2012

Finite State Machines

Contents

Even Binary Numbers


[Font] [Default] [Show] [Resize] [History] [Profile]


Even Binary Numbers - Abtsracted


[Font] [Default] [Show] [Resize] [History] [Profile]

Divisible by Three (decimal)


[Font] [Default] [Show] [Resize] [History] [Profile]

What is the function


[Font] [Default] [Show] [Resize] [History] [Profile]


What is the function


[Font] [Default] [Show] [Resize] [History] [Profile]

What is the function


[Font] [Default] [Show] [Resize] [History] [Profile]