Wednesday, August 31, 2016

DFA to accept string with even a and even b


Procedure:
1. Make a state diagram for DFA having even a and even b

2. Trace a state-table with information from (1)
3. Write a program to emulate the behavior of given DFA with the rules provided by (2)
If you need further elaboration in this topic^(i.e. Procedure), please drop a comment and we'll post DFA state-diagram and state-table also.
public class DfaEvenAB {
    public static void main(String[] args) {
        //Implementing DFA with even a and b
        String state="q0";
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the String:");
       String exp=sc.nextLine();
       HashMap a = new HashMap();
       HashMap b = new HashMap();
       a.put("q0","q1");
       a.put("q1","q0");
       a.put("q2","q3");
       a.put("q3","q2");
       b.put("q0","q3");
       b.put("q1","q2");
       b.put("q2","q1");
       b.put("q3","q0");
       
        System.out.print("Tracing DFA:\nstart=q0");
        for(int i=0;i<exp.length();i++){
            String str=""+exp.charAt(i);
            if(str.equals("a")){
                state=(String)a.get(state);
            }else if(str.equals("b")){
                state=(String)b.get(state);
            }
            System.out.print("-->"+state);
        }
        if(state.equals("q0")){
            System.out.println("\nString Accepted");
        }else{
            System.out.println("\nString not Accepted. Try another String.");
        }
    }
}

Output:


When String is Accepted:

When String is not accepted:


Blogger Comments:


Emoticon Emoticon

Most read this week!