# Designing Deterministic Finite Automata (Set 1)

Last Updated : 20 Feb, 2024

## C++

 `// dfa that accepts atleast 2 strings or more` `// alphabet = {a,b}` `#include ` `#include `   `using` `namespace` `std;`   `// initialize dfa variable` `// A=0,B=1,C=2` `int` `dfa = 0;` `// function for state A` `void` `stateA(``char` `n)` `{` `    ``/*here if char is a or b` `    ``there is a transition` `    ``from stateA to StateB*/` `    ``if` `((n == ``'a'``) || (n == ``'A'``) || (n == ``'b'``)` `        ``|| (n == ``'B'``))` `        ``dfa = 1;` `}` `// function for state B` `void` `stateB(``char` `n)` `{` `    ``/*here if char is a or b` ` ``there is a transition` ` ``from stateB to StateC*/` `    ``if` `((n == ``'a'``) || (n == ``'A'``) || (n == ``'b'``)` `        ``|| (n == ``'B'``))` `        ``dfa = 2;` `}` `// function for state C` `void` `stateC(``char` `n)` `{` `    ``/*here if char is a or b` `    ``transition remains in stateC*/` `    ``if` `((n == ``'a'``) || (n == ``'A'``) || (n == ``'b'``)` `        ``|| (n == ``'B'``))` `        ``dfa = 2;` `}` `// checking each character's acceptance` `bool` `isAccept(string strr)` `{` `    ``// convert string to character array` `    ``// create a new array of chars to copy to (+1 for a null` `    ``// terminator)` `    ``char``* str = ``new` `char``[strr.length() + 1];` `    ``// make sure that the new string is null terminated` `    ``str[strr.length()] = ``'\0'``;` `    ``for` `(``int` `i = 0; i < strr.length(); i++) {` `        ``str[i] = strr[i];` `        ``if` `(dfa == 0)` `            ``stateA(str[i]);` `        ``else` `if` `(dfa == 1)` `            ``stateB(str[i]);` `        ``else` `            ``stateC(str[i]);` `    ``}` `    ``return` `(dfa == 2);` `    ``// since stateC is final state` `}` `int` `main()` `{` `    ``string str1 = ``"a"``;` `    ``// checking if string is accepted` `    ``if` `(isAccept(str1) == ``true``)` `        ``cout << ``"Accepted"` `<< endl;` `    ``else` `        ``cout << ``"not Accepted"` `<< endl;` `    ``string str2 = ``"abababab"``;` `    ``// checking if string is accepted` `    ``if` `(isAccept(str2) == ``true``)` `        ``cout << ``"Accepted"` `<< endl;` `    ``else` `        ``cout << ``"not Accepted"` `<< endl;` `    ``return` `0;` `}`

## Java

 `// dfa that accepts atleast 2 strings or more` `// alphabet = {a,b}` `import` `java.util.*;` `public` `class` `Main {` `    ``// initialize dfa variable` `    ``// A=0,B=1,C=2` `    ``static` `int` `dfa = ``0``;` `    ``// method for state A` `    ``static` `void` `stateA(``char` `n)` `    ``{` `        ``/*here if char is a or b` `        ``there is a transition` `        ``from stateA to StateB*/` `        ``if` `((n == ``'a'``) || (n == ``'A'``) || (n == ``'b'``)` `            ``|| (n == ``'B'``))` `            ``dfa = ``1``;` `    ``}` `    ``static` `void` `stateB(``char` `n)` `    ``{` `        ``/*here if char is a or b` `     ``there is a transition` `     ``from stateB to StateC*/` `        ``if` `((n == ``'a'``) || (n == ``'A'``) || (n == ``'b'``)` `            ``|| (n == ``'B'``))` `            ``dfa = ``2``;` `    ``}` `    ``static` `void` `stateC(``char` `n)` `    ``{` `        ``/*here if char is a or b` `        ``transition remains in stateC*/` `        ``if` `((n == ``'a'``) || (n == ``'A'``) || (n == ``'b'``)` `            ``|| (n == ``'B'``))` `            ``dfa = ``2``;` `    ``}` `    ``// checking each character's acceptance` `    ``static` `boolean` `isAccept(String strr)` `    ``{` `        ``// convert string to character array` `        ``char` `str[] = strr.toCharArray();` `        ``for` `(``int` `i = ``0``; i < str.length; i++) {` `            ``if` `(dfa == ``0``)` `                ``stateA(str[i]);` `            ``else` `if` `(dfa == ``1``)` `                ``stateB(str[i]);` `            ``else` `                ``stateC(str[i]);` `        ``}` `        ``return` `(dfa == ``2``);` `        ``// since stateC is final state` `    ``}` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``String str1 = ``"a"``;` `        ``// checking if string is accepted` `        ``if` `(isAccept(str1) == ``true``)` `            ``System.out.println(``"Accepted"``);` `        ``else` `            ``System.out.println(``"not Accepted"``);` `        ``String str2 = ``"abababab"``;` `        ``// checking if string is accepted` `        ``if` `(isAccept(str2) == ``true``)` `            ``System.out.println(``"Accepted"``);` `        ``else` `            ``System.out.println(``"not Accepted"``);` `    ``}` `}`

## Python3

 `# DFA that accepts at least 2 strings or more` `# Alphabet = {a, b}`   `# Initialize DFA variable` `# A=0, B=1, C=2` `dfa ``=` `0`   `# Function for state A` `def` `stateA(n):` `    ``# If char is 'a' or 'b', transition to State B` `    ``if` `n.lower() ``in` `{``'a'``, ``'b'``}:` `        ``global` `dfa` `        ``dfa ``=` `1`   `# Function for state B` `def` `stateB(n):` `    ``# If char is 'a' or 'b', transition to State C` `    ``if` `n.lower() ``in` `{``'a'``, ``'b'``}:` `        ``global` `dfa` `        ``dfa ``=` `2`   `# Function for state C` `def` `stateC(n):` `    ``# If char is 'a' or 'b', remain in state C` `    ``if` `n.lower() ``in` `{``'a'``, ``'b'``}:` `        ``global` `dfa` `        ``dfa ``=` `2`   `# Checking each character's acceptance` `def` `is_accept(input_str):` `    ``global` `dfa` `    ``# Iterate over each character in the input string` `    ``for` `char ``in` `input_str:` `        ``if` `dfa ``=``=` `0``:` `            ``stateA(char)` `        ``elif` `dfa ``=``=` `1``:` `            ``stateB(char)` `        ``else``:` `            ``stateC(char)`   `    ``return` `dfa ``=``=` `2`  `# State C is the final state`   `# Main function` `def` `main():` `    ``str1 ``=` `"a"` `    ``# Checking if string is accepted` `    ``if` `is_accept(str1):` `        ``print``(``"Accepted"``)` `    ``else``:` `        ``print``(``"Not Accepted"``)`   `    ``str2 ``=` `"abababab"` `    ``# Checking if string is accepted` `    ``if` `is_accept(str2):` `        ``print``(``"Accepted"``)` `    ``else``:` `        ``print``(``"Not Accepted"``)`   `if` `__name__ ``=``=` `"__main__"``:` `    ``main()`

Prerequisite – Designing finite automata In this article, we will see some designing of Deterministic Finite Automata (DFA).Â

Prob

lem-1: Construction of a DFA for the set of string over {a, b} such that length of the string |w|=2 i.e, length of the string is exactly 2. Explanation – The desired language will be like:

`L = {aa, ab, ba, bb} `

The state transition diagram of the language will be like: Here, State A represent set of all string of length zero (0), state B represent set of all string of length one (1), state C represent set of all string of length two (2). State C is the final state and D is the dead state it is so because after getting any alphabet as input it will not go into final state ever.

`Number of states: n+2Where n is |w|=n `

The above automata will accept all the strings having the length of the string exactly 2. When the length of the string is 1, then it will go from state A to B. When the length of the string is 2, then it will go from state B to C and when the length of the string is greater than 2, then it will go from state C to D (Dead state) and after it from state D TO D itself.Â

## C++

 `#include ` `#include `   `// Check string in state A` `void` `checkStateA(``const` `std::string& n);`   `// Transition to state B` `void` `stateB(``const` `std::string& n);`   `// Transition to state C` `void` `stateC(``const` `std::string& n);`   `int` `main() {` `    ``// Take input` `    ``std::string n;` `    ``std::cout << ``"Enter a string: "``;` `    ``std::cin >> n;` `     `  `    ``// Check state A` `    ``checkStateA(n);`   `    ``return` `0;` `}`   `// Check string in state A` `void` `checkStateA(``const` `std::string& n) {` `    ``// If the length of the string is one, print not accepted` `    ``if` `(n.length() == 1) {` `        ``std::cout << ``"string not accepted"` `<< std::endl;` `    ``} ``else` `{` `        ``// Pass the string to state B for further transitions` `        ``if` `(n[0] == ``'a'` `|| n[0] == ``'b'``) {` `            ``stateB(n.substr(1));` `        ``}` `    ``}` `}`   `// Transition to state B` `void` `stateB(``const` `std::string& n) {` `    ``// If the length is not 1, print not accepted` `    ``if` `(n.length() != 1) {` `        ``std::cout << ``"string not accepted"` `<< std::endl;` `    ``} ``else` `{` `        ``// Pass the string to state C` `        ``stateC(n.substr(1));` `    ``}` `}`   `// Transition to state C` `void` `stateC(``const` `std::string& n) {` `    ``// If the length becomes zero, print accepted; else, not accepted` `    ``if` `(n.empty()) {` `        ``std::cout << ``"string accepted"` `<< std::endl;` `    ``} ``else` `{` `        ``std::cout << ``"string not accepted"` `<< std::endl;` `    ``}` `}`

## Java

 `import` `java.util.Scanner;`   `public` `class` `StateMachine {`   `    ``public` `static` `void` `main(String[] args) {` `        ``// Set the input string directly in the code` `        ``String inputString = ``"aa"``;`   `        ``// Check state A` `        ``checkStateA(inputString);` `    ``}`   `    ``// Check string in state A` `    ``static` `void` `checkStateA(String n) {` `        ``// If the length of the string is one, print not accepted` `        ``if` `(n.length() == ``1``) {` `            ``System.out.println(``"string not accepted"``);` `        ``} ``else` `{` `            ``// Pass the string to state B for further transitions` `            ``if` `(n.charAt(``0``) == ``'a'` `|| n.charAt(``0``) == ``'b'``) {` `                ``stateB(n.substring(``1``));` `            ``}` `        ``}` `    ``}`   `    ``// Transition to state B` `    ``static` `void` `stateB(String n) {` `        ``// If the length is not 1, print not accepted` `        ``if` `(n.length() != ``1``) {` `            ``System.out.println(``"string not accepted"``);` `        ``} ``else` `{` `            ``// Pass the string to state C` `            ``stateC(n.substring(``1``));` `        ``}` `    ``}`   `    ``// Transition to state C` `    ``static` `void` `stateC(String n) {` `        ``// If the length becomes zero, print accepted; else, not accepted` `        ``if` `(n.isEmpty()) {` `            ``System.out.println(``"string accepted"``);` `        ``} ``else` `{` `            ``System.out.println(``"string not accepted"``);` `        ``}` `    ``}` `}`

## Python3

 `#check string in` `#in state A` `def` `checkStateA(n):` `    `  `    ``#if length of` `    ``#string is one` `    ``#print not accepted` `    ``if``(``len``(n)``=``=``1``):` `        ``print``("string ``not` `accepted")` `    ``else``:   ` `        ``#pass string to stateB to` `        ``#to check further transitions` `        ``if``(n[``0``]``=``=``'a'` `or` `n[``0``]``=``=``'b'``):` `            ``stateB(n[``1``:])` `            `  `            `  `def` `stateB(n):` `    ``#here if length ` `    ``#is not 1 print#string not accepted` `    ``if``(``len``(n)!``=``1``):` `        ``print``("string ``not` `accepted")` `    ``else``:` `        ``#else pass string ` `        ``#to state c` `        ``stateC(n[``1``:])` `def` `stateC(n):` `    ``#here if length ` `    ``#becomes zero` `    ``#print accepted` `    ``#else not accepted` `    ``if` `(``len``(n)``=``=``0``):` `        ``print``("string accepted")` `    ``else``:` `        ``print``("string ``not` `accepted")` `    `  `    `  `#take input    ` `n``=``input``()` `checkStateA(n)`

## C#

 `using` `System;`   `class` `StateMachine` `{` `    ``static` `void` `Main()` `    ``{` `        ``// Set the input string directly in the code` `        ``string` `inputString = ``"aa"``;`   `        ``// Check state A` `        ``CheckStateA(inputString);` `    ``}`   `    ``// Check string in state A` `    ``static` `void` `CheckStateA(``string` `n)` `    ``{` `        ``// If the length of the string is one, print not accepted` `        ``if` `(n.Length == 1)` `        ``{` `            ``Console.WriteLine(``"string not accepted"``);` `        ``}` `        ``else` `        ``{` `            ``// Pass the string to state B for further transitions` `            ``if` `(n[0] == ``'a'` `|| n[0] == ``'b'``)` `            ``{` `                ``StateB(n.Substring(1));` `            ``}` `        ``}` `    ``}`   `    ``// Transition to state B` `    ``static` `void` `StateB(``string` `n)` `    ``{` `        ``// If the length is not 1, print not accepted` `        ``if` `(n.Length != 1)` `        ``{` `            ``Console.WriteLine(``"string not accepted"``);` `        ``}` `        ``else` `        ``{` `            ``// Pass the string to state C` `            ``StateC(n.Substring(1));` `        ``}` `    ``}`   `    ``// Transition to state C` `    ``static` `void` `StateC(``string` `n)` `    ``{` `        ``// If the length becomes zero, print accepted; else, not accepted` `        ``if` `(``string``.IsNullOrEmpty(n))` `        ``{` `            ``Console.WriteLine(``"string accepted"``);` `        ``}` `        ``else` `        ``{` `            ``Console.WriteLine(``"string not accepted"``);` `        ``}` `    ``}` `}` `// code is contributed by utkarsh`

## Javascript

 `// Check string in state A` `function` `checkStateA(n) {` `    ``// If the length of the string is one, print not accepted` `    ``if` `(n.length === 1) {` `        ``console.log(``"string not accepted"``);` `    ``} ``else` `{` `        ``// Pass the string to state B for further transitions` `        ``if` `(n[0] === ``'a'` `|| n[0] === ``'b'``) {` `            ``stateB(n.substring(1));` `        ``}` `    ``}` `}`   `// Transition to state B` `function` `stateB(n) {` `    ``// If the length is not 1, print not accepted` `    ``if` `(n.length !== 1) {` `        ``console.log(``"string not accepted"``);` `    ``} ``else` `{` `        ``// Pass the string to state C` `        ``stateC(n.substring(1));` `    ``}` `}`   `// Transition to state C` `function` `stateC(n) {` `    ``// If the length becomes zero, print accepted; else, not accepted` `    ``if` `(n.length === 0) {` `        ``console.log(``"string accepted"``);` `    ``} ``else` `{` `        ``console.log(``"string not accepted"``);` `    ``}` `}`   `// Main function` `function` `main() {` `    ``// Take input` `    ``const readline = require(``'readline'``);` `    ``const rl = readline.createInterface({` `        ``input: process.stdin,` `        ``output: process.stdout` `    ``});`   `    ``rl.question(``"Enter a string: "``, ``function` `(n) {` `        ``// Check state A` `        ``checkStateA(n);` `        ``rl.close();` `    ``});` `}`   `// Call the main function` `main();`

Problem-2: Construction of a DFA for the set of string over {a, b} such that length of the string |w|>=2 i.e, length of the string should be at least 2. Explanation – The desired language will be like:

`L = {aa, ab, ba, bb, aaa, aab, aba, abb........} `

The state transition diagram of the language will be like: Here, State A represent set of all string of length zero (0), state B represent set of all string of length one (1), and state C represent set of all string of length two (2).

`Number of states: n+1Where n is |w|>=n `

The above automata will accept all the strings having the length of the string at least 2. When the length of the string is 1, then it will go from state A to B. When the length of the string is 2, then it will go from state B to C and lastly when the length of the string is greater than 2, then it will go from state C to C itself.Â

## Python3

 `#check string in` `#in state A` `def` `checkStateA(n):` `    `  `    ``#if length of` `    ``#string is one` `    ``#print not accepted` `    ``if``(``len``(n)``=``=``1``):` `        ``print``("string ``not` `accepted")` `    ``else``:   ` `        ``#pass string to stateB to` `        ``#to check further transitions` `        ``if``(n[``0``]``=``=``'a'` `or` `n[``0``]``=``=``'b'``):` `            ``stateB(n[``1``:])` `            `  `            `  `def` `stateB(n):` `    `  `    ``#here if length ` `    ``#is less than 1 ` `    ``#printstring not accepted` `    ``if``(``len``(n)<``1``):` `        ``print``("string ``not` `accepted")` `    ``else``:` `        `  `        ``#else pass string ` `        ``#to state c` `        ``stateC(n[``1``:])` `        `  `        `  `def` `stateC(n):` `    ``#here if length of string ` `    ``#is greater than equal to zero` `    ``#print accepted` `    ``#else not accepted` `    ``if` `(``len``(n)>``=``0``):` `        ``print``("string accepted")` `    ``else``:` `        ``print``("string ``not` `accepted")` `    `  `    `  `#take input    ` `n``=``input``()` `checkStateA(n)`

Problem-3: Construction of a DFA for the set of string over {a, b} such that length of the string |w|<=2 i.e, length of the string is atmost 2.
Explanation – The desired language will be like:

`L = {?, aa, ab, ba, bb} `

The state transition diagram of the language will be like: Â

Here, State A represent set of all string of length zero (0), state B represent set of all string of length one (1), state C represent set of all string of length two (2), state A, B, C is the final state and D is the dead state it is so because after getting any alphabet as input it will not go into final state ever.

`Number of states: n+2Where n is |w|<=n `

The above automata will accept all the strings having the length of the string at most 2. When the length of the string is 1, then it will go from state A to B. When the length of the string is 2, then it will go from state B to C and lastly when the length of the string is greater than 2, then it will go from state C to D (Dead state).Â

## Python3

 `#check string in` `#in state A` `def` `checkStateA(n):` `    `  `    ``#if only two transition occurs ` `    ``#then print string accepted` `  `  `    ``if``(n[``0``]``=``=``'a'` `or` `n[``0``]``=``=``'b'``):` `        ``stateB(n[``1``:])` `            `  `            `  `def` `stateB(n):` `    `  `    ``#if length is 0 ` `    ``#print accepted` `    ``if``(``len``(n)``=``=``0``):` `        ``print``("string accepted")` `    ``else``:` `        ``stateC(n[``1``:])` `        `  `        `  `def` `stateC(n):` `    ``#if length is 0 ` `    ``#print accepted` `    ``#else not accepted` `    ``if` `(``len``(n)``=``=``0``):` `        ``print``("string accepted")` `    ``else``:` `        ``print``("string ``not` `accepted")` `    `  `    `  `#take input    ` `n``=``input``()` `checkStateA(n)`

Previous
Next