Converting a. NET algorithm to JS

Asked

Viewed 196 times

2

Fellas, I’m having a little problem converting an algorithm. In the algorithm in .net i have the following conditional structure:

if (')' == caracter){
    String item = pilha.Pop().ToString();
    while (!item.Equals("(")){
        resultado += item;
        item = pilha.Pop().ToString();
    }
}

Throwing everything to javaScript would be as follows:

if (')' == caracter){
    var item = pilha.pop();
    while (item != '('){
        resultado += item; //Corrigido
        item = pilha.pop();
    }
}

In my view while (!item.Equals("(")){ would be the equivalent of a while (item != '('){

Only in this condition it is going into infinite looping, ie the algorithm is not running the way it should.... Could someone give me a Help on the function Equals and the operator ! in .net?

My interpretation was "very" wrong?

-------Interpretation of the whole code: .NET

private String funcao(String expressao){
    String resultado = null;
    Stack pilha = new Stack();
    char caracter;
    int prioridade = 0;

    for(int i = 0; i < expressao.Length; i++){
        caracter = expressao[i];

        if(IsOperando(caracter)){
            resultado += caracter;
        }else if (IsOperador(caracter)){
            prioridade = ObterPrioridade(caracter);
            while((pilha.Count != 0) && (ObterPrioridade(Convert.ToChar(pilha.Peek())) >= prioridade)){
                resultado += pilha.Pop().ToString();
            }

            pilha.Push(caracter);
        }else if ('(' == caracter){
            pilha.Push(caracter);
        }else if (')' ==caracter){
            String item = pilha.Pop().ToString();
            while (!item.Equals("(")){
                resultado += item;
                item = pilha.Pop().ToString();
            }
        }
    }

    while(pilha.Count != 0){
        resultado += pilha.Pop().ToString();
    }

    return resultado;
}

Interpreted to JS:

function funcao(){
    var arrayDeCaracteres = "((A + B) * C – (D – E)) ^ (F – G)";
    var pilha = new Array;
    var prioridade = 0;
    var caracter = ""; var resultado = "";

    for(i = 0; i < arrayDeCaracteres.length; i++){
        caracter = arrayDeCaracteres[i];

        if(operando(caracter)){
            resultado += caracter;
        }else if (operador(caracter)){
            prioridade = obterPrioridade(caracter);
            aux = pilha.pop();
            aux2 = obterPrioridade(aux);
            pilha.push(aux);
            while((pilha.length  > 1) && (obterPrioridade(aux2 >= prioridade))){
                resultado += pilha.pop();
            }
            //Insere o objeto no topo da pilha
            pilha.push(caracter);
        }else if ('(' == caracter){
            //Insere o objeto no topo da pilha
            pilha.push(caracter);
        }else if (')' == caracter){
            var item = pilha.pop();
            while (item != '('){
                resultado += item;
                //Recupera e remove o objeto do topo da pilha
                item = pilha.pop();
            }
        }
    }

    while(pilha.length > 1){
        resultado += pilha.pop();
    }
}

Function ObterPrioridade, IsOperando and IsOperador in .NET:

private int ObterPrioridade(char caracter){
    int retorno= 0;
    String pri2 = "+-";
    String pri3 = "*/";
    if('(' == caracter){
        retorno = 1;
    }else if(pri2.IndexOf(caracter) >= 0) {
        retorno = 2;
    }else if(pri3.IndexOf(caracter) >= 0){
        retorno = 3;
    }else if ('^' == caracter){
        retorno = 4;
    }
    return retorno;
}

private bool IsOperando(char caracter){
    String letras = "ABCDEFGHIJKLMNOPQRSTUVXZ";
    return (letras.IndexOf(caracter) >= 0);
}

private bool IsOperador(char caracter){
    String operadores = "+-*/^";
    return (operadores.IndexOf(caracter) >= 0);
}

Function obterPrioridade, operando and operador in JS:

function operando(caracter){
    var regex = /^[a-zA-Z]+$/;
    if(regex.test(caracter)){
        return true;
    }else{
        return false;
    }
}

function operador(caracter){
    var regex = /^[*+-–/]+$/gi;
    if(regex.test(caracter)){
        return true;
    }else{
        return false;
    }
}

function obterPrioridade(caracter){
    var retorno= 0;
    var regex1 = /^[+-–]+$/gi;
    var regex2 = /^[*/]+$/gi;

    if('(' == caracter){
        retorno = 1;
    }else if(regex1.test(caracter)){
        retorno = 2;
    }else if(regex2.test(caracter)){
        retorno = 3;
    }else if ('^' == caracter){
        retorno = 4;
    }
    return retorno;
}

EXPLANATION OF THE ALGORITHM:

The algorithm provides for the conversion of an Infixa mathematical expression into Posfixa....

What to be a infix expression?

Natural expressions, like they’re usually written, like: ( a + b ) * ( c - d )

What to be a posfixa expression?

Expressions where operators are positioned after operations so that parentheses are not required, type a b + c d - *

There’s a priority operator rule and everything, it’s really complicated, but the algorithm is kind of simple

  • What has this array pilha?

  • is stacking operators of type " +-*/ " in addition to characters " () "

  • 1

    Can you give an example? What is the pilha.length? If one of the elements of this array does not have the ( this loop will be infinite even

  • Dude, I ran them both here and it worked out. Just be careful if you’re ever gonna see the '(', because then it goes into an infinite loop.

  • So, !item.Equals("(") would be the same as item != '(' even?

  • Yes... the same thing.

  • @Marcelobonifazio this code seems to me fragile. Hence I ask for examples to help optimize. Otherwise your "translation" between languages seems to me correct apart from the fact that resultado in its version have only the value of the last iteration and not a concatenation of the iterations.

  • Just complementing what I said before, it’s the same thing for this kind of application.

  • In fact what will happen there is that when the stack does not have the character you are comparing, one time, the loop will ask the pop() of an empty list and then will give error.

  • I’ll pass the full algorithm for testing

  • Ready.... has some functions of . Net like Peek (which, if I’m not mistaken, is an extra class) that are not native to JS, so I kind of did a gambit there, and preferred to work with RegEx to find out if it is operating or operator

  • A, e @Sergio valeu por toque, I fixed there the last iteration to concatenate the value of the item

  • Equal is used to compare objects while the != operator is used to compare Primitive types.

Show 8 more comments

1 answer

1

If you are using IE or some other browsers that do not correctly implement it, this expression will not work:

 caracter = expressao[i];  // nem sempre funciona

The result of this expression in IE is undefined. In Javascript, you must use the expression:

 caracter = expressao.charAt(i); // sempre funciona

Also, instead of building arrays like this:

 var pilha = new Array; // funciona, mas não é legal...
                        // alguém ainda vai editar e dar um
                        //  new Array(32) ou Array(32, 3) e entender tudo errado!

Do so:

 var pilha = []; // funcionar e você pode inicializar tranquilamente!

Who is used to javascript, the second expression is much simpler and readable. You will also see that it is very common to start javascript arrays with values already. Use the first expression new Array() with parameters leads to many erroneous results, because the order and quantity of parameters use not obvious constructors!

No more the "translation" is ok!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.