# Program to build DFA that starts and end with ‘a’ from input (a, b) in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Given a DFA string of characters ‘a’ and ‘b’, which should start and end with the character ‘a’ the task is to find whether the string starts and ends with ‘a’ through a DFA.

What is DFA(Deterministic Finite Automata)?

In theory of computation, a branch of theoretical computer science, Deterministic Finite Automata is a finite state machine which accepts or reject strings of symbols. Deterministic refers to the uniqueness of the computation to run.

For finding the string by a DFA and the string should start and end with ‘a’ from the input (a, b). Since there is no concept of memory and we can only store the current character, the DFA can't store the string provided, else we can easily just check the first and last character of the sequence/string given to us.

## Example

Input: a b b a
Output: yes
Explanation: The input string starts and ends with ‘a’

Input: a a a b a b
Output: no

Approach we are following to solve the above problem −

So, we will make a DFA for the above stated problem and then will solve the problem according to the DFA we create.

dfa.jpg

## Algorithm

Start
Step 1-> In main()
Call function srand(time(0)) to generate random numbers
Declare variable as int max = 1 + rand() % 15
Declare and set int i = 0
While(i < max)
Declare char data = 'a' + rand() % 2
Print data
Increment i
IF data = 'a'
IF(i = max)
Print "YES"
End
Loop While (i < max)
Set data = 'a' + rand() % 2
Print data
Increment i
If (data = 'a' AND i = max)
Print YES\n
End
Else IF(i = max)
Print NO
End
End
End
Else
Loop While (i < max)
Set data = 'a' + rand() % 2
Print data
Increment i
End
Print NO
End
End
Stop

## Example

Live Demo

#include <iostream>
#include <time.h>
using namespace std;
int main() {
// for generating random numbers
srand(time(0));
int max = 1 + rand() % 15;
int i = 0;
while (i < max) {
char data = 'a' + rand() % 2;
cout << data << " ";
i++;
if (data == 'a') {
if (i == max)
cout << "YES\n";
while (i < max) {
data = 'a' + rand() % 2;
cout << data << " ";
i++;
if (data == 'a' && i == max) {
cout << "\nYES\n";
} else if (i == max) {
cout << "\nNO\n";
}
}
} else {
while (i < max) {
data = 'a' + rand() % 2;
cout << data << " ";
i++;
}
cout << "\nNO\n";
}
}
return 0;
}

## Output

b b a b a b a b b b b b
NO