Search code examples
c#arraysfor-loopautomata-theory

how to transfer between arrays in c#?


I have a project in Automata theory, and I want to convert an algorithm into programming language( no matter what programming language used to solve this question)

Well, I have these orders

we enter a string and then we convert it to char so we can compare,

for example we entered this input

01001

to make it clear, I will add more inputs to know what I mean,

01000001

{valid input}

101101

{Wrong input}

0

{Wrong input}

we will check if the first digit is 0 if yes, we copy this string to another array 1, and then convert it to with 1 if it's same we copy it to array 2, then here we will need to enter a loop using for or foreach, we want to check if the next values are 0 ( without last char) so I used a.length-1 to make sure it's won't use last one, and when we see new value which is 1, we move to the last array and must be 1. we will message using Console.WriteLine(""); that the program follows the order

I made something similar which is this (in C#):

string s= Console.ReadLine();
var a = s.ToCharArray();

Console.WriteLine("Original String: {0}",s);

//for (int k = 4; k < a.Length; k++) {
if (a[0] == '0' && a[1] == '1' && a[a.Length-1] == '1') {

    for (int r = 2; r < a.Length-1; r++) {
        if (a[r] == '0')
        {
            Console.WriteLine("The Language is Right.");

        }              
    }               
}

how do I make new arrays and copy and use it to check out


Solution

  • The straightforward way of implementing a finite automaton is to loop over the input and store the state in a variable:

    string s= Console.ReadLine();
    int state = 0;
    foreach (char c in s.ToCharArray())
    {
        if (state == 0 && c == '0')
            state = 1;
        else if (state == 0 && c == '1')
            state = -1;
        else if (state == 1 && c == '1')
            state = 2;
        else if (state == 1 && c == '0')
            state = -1;
        else if (state == 2 && c == '1')
            state = 3;
        else if (state == 3)
            state = -1;
    }
    bool accepted = state == 3;
    Console.WriteLine(accepted);