The Wayback Machine - https://web.archive.org/web/20240130055524/https://www.geeksforgeeks.org/nfa-which-accepts-set-of-strings-over-an-alphabet-0-1-2-such-that-the-final-digit-has-appeared-before/
Open In App
Related Articles

NFA which accepts set of strings over an alphabet {0, 1, 2} such that the final digit has appeared before

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Prerequisite – Introduction of Finite Automata 

C++ Program to construct an NFA which accepts the set of strings over an alphabet {0, 1, 2} such that the final digit has appeared before.

Examples: 

Input : 01101 
Output : Accepted

Input : 012
Output : Not Accepted

Input : 2
Output : Not Accepted

Input : 0122
Output : Accepted 

Explanation: 

In the first example, 01101, the last digit ‘1’ occurred at letter number 2 and 3 of the string. Hence it is accepted. In the second example, 012, the occurrence of ‘2’ is only at the last place. Hence it is rejected. Similarly, with the third example, 2 is rejected. In the last example, the last digit ‘2’ occurred before end of the string hence it is Accepted. 

Approach: 

  1. Construct a start state.
  2. Construct 3 states for inputs of 0, 1 and 2.
  3. Repeat the loops in all states for all the inputs.
  4. Connect all the states with a final state.

NFA State Transaction Diagram: 

Implementation :

C++




#include <bits/stdc++.h>
using namespace std;
// function of state one or starting state
void q1(string s, int pos, int len);
// function of state two
void q2(string s, int pos, int len);
// function of state three
void q3(string s, int pos, int len);
// function of state four
void q4(string s, int pos, int len);
// function of state five
void q5(string s, int pos, int len);
// See diagram for help
vector<string> states;
int accepted = 0;
// Uncomment this function and the function calls to see
// the path of string from the start state to end state
/*
void printVector()
{
    for (auto i = states.begin(); i != states.end(); i++)
        cout << *i << " ";
    cout << endl;
}
*/
void q5(string s, int pos, int len)
{
    states.push_back("Q5->");
    if (pos == len) {
        // printVector();
        accepted = 1;
    }
    else {
        states.push_back("Dead");
        // printVector();
        states.pop_back();
    }
    states.pop_back();
    return;
}
void q4(string s, int pos, int len)
{
    states.push_back("Q4->");
    if (pos == len) {
        // printVector();
        states.pop_back();
        return;
    }
    if (s[pos] == '2')
        q5(s, pos + 1, len);
    q4(s, pos + 1, len);
    states.pop_back();
    return;
}
void q3(string s, int pos, int len)
{
    states.push_back("Q3->");
    if (pos == len) {
        // printVector();
        states.pop_back();
        return;
    }
    if (s[pos] == '1')
        q5(s, pos + 1, len);
    q3(s, pos + 1, len);
    states.pop_back();
    return;
}
 
void q2(string s, int pos, int len)
{
    states.push_back("Q2->");
    if (pos == len) {
        // printVector();
        states.pop_back();
        return;
    }
    if (s[pos] == '0')
        q5(s, pos + 1, len);
    q2(s, pos + 1, len);
    states.pop_back();
    return;
}
 
void q1(string s, int pos, int len)
{
    states.push_back("Q1->");
    if (pos == len) {
        // printVector();
        states.pop_back();
        return;
    }
    if (s[pos] == '0')
        q2(s, pos + 1, len);
    else if (s[pos] == '1')
        q3(s, pos + 1, len);
    else if (s[pos] == '2')
        q4(s, pos + 1, len);
 
    q1(s, pos + 1, len);
    states.pop_back();
    return;
}
 
int main()
{
    string s;
    // cin >> s;
    s = "01101";
 
    int pos = 0;
    q1(s, pos, s.length());
 
    if (accepted)
        cout << "Accepted" << endl;
    else
        cout << "Not Accepted" << endl;
    return 0;
}


Python3




# function of state one or starting state
def q1(s, pos, length):
    global accepted, states
    states.append("Q1->")
    if pos == length:
        # print(states)
        states.pop()
        return
    if s[pos] == '0':
        q2(s, pos + 1, length)
    elif s[pos] == '1':
        q3(s, pos + 1, length)
    elif s[pos] == '2':
        q4(s, pos + 1, length)
    q1(s, pos + 1, length)
    states.pop()
 
# function of state two
def q2(s, pos, length):
    global accepted, states
    states.append("Q2->")
    if pos == length:
        # print(states)
        states.pop()
        return
    if s[pos] == '0':
        q5(s, pos + 1, length)
    q2(s, pos + 1, length)
    states.pop()
 
# function of state three
def q3(s, pos, length):
    global accepted, states
    states.append("Q3->")
    if pos == length:
        # print(states)
        states.pop()
        return
    if s[pos] == '1':
        q5(s, pos + 1, length)
    q3(s, pos + 1, length)
    states.pop()
 
# function of state four
def q4(s, pos, length):
    global accepted, states
    states.append("Q4->")
    if pos == length:
        # print(states)
        accepted = 1
        states.pop()
        return
    if s[pos] == '2':
        q5(s, pos + 1, length)
    q4(s, pos + 1, length)
    states.pop()
 
# function of state five
def q5(s, pos, length):
    global accepted, states
    states.append("Q5->")
    if pos == length:
        # print(states)
        accepted = 1
        states.pop()
        return
    states.append("Dead")
    # print(states)
    states.pop()
    states.pop()
    return
 
# Uncomment this function and the function calls to see
# the path of string from the start state to end state
'''
def printVector():
    global states
    for i in states:
        print(i, end=" ")
    print()
'''
 
states = []
accepted = 0
 
# s = input()
s = "01101"
pos = 0
q1(s, pos, len(s))
 
if accepted:
    print("Accepted")
else:
    print("Not Accepted")


C#




using System;
using System.Collections.Generic;
 
namespace FiniteAutomata
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "01101";
            int pos = 0;
            List<string> states = new List<string>();
            int accepted = 0;
 
            Q1(s, pos, s.Length, states, ref accepted);
 
            if (accepted == 1)
                Console.WriteLine("Accepted");
            else
                Console.WriteLine("Not Accepted");
        }
 
        static void Q1(string s, int pos, int len, List<string> states, ref int accepted)
        {
            states.Add("Q1->");
            if (pos == len)
            {
                // printVector();
                states.RemoveAt(states.Count - 1);
                return;
            }
 
            if (s[pos] == '0')
                Q2(s, pos + 1, len, states, ref accepted);
            else if (s[pos] == '1')
                Q3(s, pos + 1, len, states, ref accepted);
            else if (s[pos] == '2')
                Q4(s, pos + 1, len, states, ref accepted);
 
            Q1(s, pos + 1, len, states, ref accepted);
            states.RemoveAt(states.Count - 1);
        }
 
        static void Q2(string s, int pos, int len, List<string> states, ref int accepted)
        {
            states.Add("Q2->");
            if (pos == len)
            {
                // printVector();
                states.RemoveAt(states.Count - 1);
                return;
            }
 
            if (s[pos] == '0')
                Q5(s, pos + 1, len, states, ref accepted);
 
            Q2(s, pos + 1, len, states, ref accepted);
            states.RemoveAt(states.Count - 1);
        }
 
        static void Q3(string s, int pos, int len, List<string> states, ref int accepted)
        {
            states.Add("Q3->");
            if (pos == len)
            {
                // printVector();
                states.RemoveAt(states.Count - 1);
                return;
            }
 
            if (s[pos] == '1')
                Q5(s, pos + 1, len, states, ref accepted);
 
            Q3(s, pos + 1, len, states, ref accepted);
            states.RemoveAt(states.Count - 1);
        }
 
        static void Q4(string s, int pos, int len, List<string> states, ref int accepted)
        {
            states.Add("Q4->");
            if (pos == len)
            {
                // printVector();
                states.RemoveAt(states.Count - 1);
                return;
            }
 
            if (s[pos] == '2')
                Q5(s, pos + 1, len, states, ref accepted);
 
            Q4(s, pos + 1, len, states, ref accepted);
            states.RemoveAt(states.Count - 1);
        }
 
        static void Q5(string s, int pos, int len, List<string> states, ref int accepted)
        {
            states.Add("Q5->");
            if (pos == len)
            {
                // printVector();
                accepted = 1;
            }
            else
            {
                states.Add("Dead");
                // printVector();
                states.RemoveAt(states.Count - 1);
            }
 
            states.RemoveAt(states.Count - 1);
            return;
        }
    }
}


Javascript




// function of state one or starting state
function q1(s, pos, length) {
  if (pos == length) {
    // console.log(states);
    states.pop();
    return;
  }
  states.push("Q1->");
  if (s[pos] == "0") {
    q2(s, pos + 1, length);
  } else if (s[pos] == "1") {
    q3(s, pos + 1, length);
  } else if (s[pos] == "2") {
    q4(s, pos + 1, length);
  }
  q1(s, pos + 1, length);
  states.pop();
}
 
// function of state two
function q2(s, pos, length) {
  if (pos == length) {
    // console.log(states);
    states.pop();
    return;
  }
  states.push("Q2->");
  if (s[pos] == "0") {
    q5(s, pos + 1, length);
  }
  q2(s, pos + 1, length);
  states.pop();
}
 
// function of state three
function q3(s, pos, length) {
  if (pos == length) {
    // console.log(states);
    states.pop();
    return;
  }
  states.push("Q3->");
  if (s[pos] == "1") {
    q5(s, pos + 1, length);
  }
  q3(s, pos + 1, length);
  states.pop();
}
 
// function of state four
function q4(s, pos, length) {
  if (pos == length) {
    // console.log(states);
    accepted = 1;
    states.pop();
    return;
  }
  states.push("Q4->");
  if (s[pos] == "2") {
    q5(s, pos + 1, length);
  }
  q4(s, pos + 1, length);
  states.pop();
}
 
// function of state five
function q5(s, pos, length) {
  if (pos == length) {
    // console.log(states);
    accepted = 1;
    states.pop();
    return;
  }
  states.push("Q5->");
  states.push("Dead");
  // console.log(states);
  states.pop();
  states.pop();
  return;
}
 
// Uncomment this function and the function calls to see
// the path of string from the start state to end state
/*
function printVector() {
  for (let i = 0; i < states.length; i++) {
    console.log(states[i], " ");
  }
  console.log();
}
*/
 
let states = [];
let accepted = 0;
 
// let s = prompt();
let s = "01101";
let pos = 0;
q1(s, pos, s.length);
 
if (accepted) {
  console.log("Accepted");
} else {
  console.log("Not Accepted");
}


Java




import java.util.*;
 
public class Main {
// function of state one or starting state
static void q1(String s, int pos, int len) {
    states.add("Q1->");
    if (pos == len) {
        // printVector();
        states.remove(states.size() - 1);
        return;
    }
    if (s.charAt(pos) == '0')
        q2(s, pos + 1, len);
    else if (s.charAt(pos) == '1')
        q3(s, pos + 1, len);
    else if (s.charAt(pos) == '2')
        q4(s, pos + 1, len);
 
    q1(s, pos + 1, len);
    states.remove(states.size() - 1);
    return;
}
 
// function of state two
static void q2(String s, int pos, int len) {
    states.add("Q2->");
    if (pos == len) {
        // printVector();
        states.remove(states.size() - 1);
        return;
    }
    if (s.charAt(pos) == '0')
        q5(s, pos + 1, len);
    q2(s, pos + 1, len);
    states.remove(states.size() - 1);
    return;
}
 
// function of state three
static void q3(String s, int pos, int len) {
    states.add("Q3->");
    if (pos == len) {
        // printVector();
        states.remove(states.size() - 1);
        return;
    }
    if (s.charAt(pos) == '1')
        q5(s, pos + 1, len);
    q3(s, pos + 1, len);
    states.remove(states.size() - 1);
    return;
}
 
// function of state four
static void q4(String s, int pos, int len) {
    states.add("Q4->");
    if (pos == len) {
        // printVector();
        states.remove(states.size() - 1);
        return;
    }
    if (s.charAt(pos) == '2')
        q5(s, pos + 1, len);
    q4(s, pos + 1, len);
    states.remove(states.size() - 1);
    return;
}
 
// function of state five
static void q5(String s, int pos, int len) {
    states.add("Q5->");
    if (pos == len) {
        // printVector();
        accepted = 1;
    }
    else {
        states.add("Dead");
        // printVector();
        states.remove(states.size() - 1);
    }
    states.remove(states.size() - 1);
    return;
}
 
// See diagram for help
static List<String> states = new ArrayList<String>();
static int accepted = 0;
 
// Uncomment this function and the function calls to see
// the path of string from the start state to end state
/*
static void printVector() {
    for (String state : states)
        System.out.print(state + " ");
    System.out.println();
}
*/
 
public static void main(String[] args) {
    String s = "01101";
    int pos = 0;
    q1(s, pos, s.length());
 
    if (accepted != 0)
        System.out.println("Accepted");
    else
        System.out.println("Not Accepted");
}
}


Output:

Accepted

Learn to code easily with our course Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!


Last Updated : 10 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads