Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

JavaScript coding problem

Options
  • 08-03-2006 8:40pm
    #1
    Closed Accounts Posts: 13


    I am having a problem with an assignment I've recieved for college.

    I have to take in a number, a maths sign (+, -, *, /), a number, another maths sign and another number. Then work out the result(It has to be mathematically correct).

    e.g. 3 + 5 * 4 => 3 + 20 = 23.

    Unfortunately I have to use a prompt to take in the maths signs. So that means no buttons.

    The only way I can think of doing this is to use a heap load of nested if else if statements. But I have estimated that it would require about 14,395 if statements. There just has to be another way.

    I'm not looking for someone to post the code for it(I do have a brain). I'm just looking for a way that doesn't involve a bucket load of if statements.

    Any help would be greatly appreciated.


Comments

  • Closed Accounts Posts: 4,943 ✭✭✭Mutant_Fruit


    post up the way you were thinking of doing it (psuedo code is enough).

    But you could do something like...

    Scan in data.
    If either operator is multiply or divide, work that section out. Then work out the other operator. based on the answer from the first section.

    Print the result....


  • Closed Accounts Posts: 13 ConnD3mned


    if(operand2 == "*")
    {
    if (operand1 == "+")
    {
    answer = num1 + (num2 * num3);
    }
    repeat for operand1 = -,*,/
    }
    else if (operand2 == "/")
    {
    if (operand1 == "+")
    {
    answer = num1 + (num2 / num3);
    }
    repeat for operand1 = -,*,/
    }

    keep repeating for operand2 = -,+


    While it would work this way it does use a lot of if statements. I was just wondering is there a way to do it without using so many of them.
    I don't think it's possible but you never know.


  • Closed Accounts Posts: 13 ConnD3mned


    Here is the code I used with all those damn if statements.

    I'm looking for a way to do the same thing but with out all those if statements and possibly cutting down on the code.


  • Registered Users Posts: 1,275 ✭✭✭bpmurray


    Have you tried using "eval"?


  • Moderators, Science, Health & Environment Moderators Posts: 8,950 Mod ✭✭✭✭mewso


    Yes indeed good old eval - http://builder.com.com/5100-6371-5169823.html
    Put your example 3 + 5 * 4 into this page http://img.com.com/i/tr/bldr/pub/evalcalc.html and see it in action.


  • Advertisement
  • Closed Accounts Posts: 4,943 ✭✭✭Mutant_Fruit


    I'll write up some code tomorrow, its late now. But that should be doable in a lot less lines :p


  • Registered Users Posts: 919 ✭✭✭timeout


    Well i've edited the code provide above to shrink it down without the use of the eval function:
    var num1 = 0;
    var num2 = 0;
    var num3 = 0;
    var operand1 = "";
    var operand2 = "";
    var spareoperand = "";
    var secone = "";
    var sectwo = "";
    var answer = 0;
    
    num1 = parseFloat(prompt("Please enter the first number ",""));
    operand1 = prompt("Please enter the first mathematical operand "."");
    num2 = parseFloat(prompt("Please enter the second number ",""));
    operand2 = prompt("Please enter the second mathematical operand "."");
    num3 = parseFloat(prompt("Please enter the third number ",""));
    
    if(operand1 == "*")
    {
        secone = num1 * num2;
        sectwo = num3;
        spareoperand = operand2;
    }
    else if (operand2 == "*")
    {
        secone = num1;
        sectwo = num2 * num3;
        spareoperand = operand1;
    }
    else if (operand1 == "/")
    {
        secone = num1 / num2;
        sectwo = num3;
        spareoperand = operand2;
    }
    else if (operand2 == "/")
    {
        secone = num1;
        sectwo = num2 / num3;
        spareoperand = operand1;
    }
    
    if (spareoperand == "+")
        {
            answer = secone + sectwo;
        }
        else if (spareoperand1 == "-")
        {
            answer = secone - sectwo;
        }
        else if (spareoperand == "*")
        {
            answer = secone * sectwo;
        }
        else if (spareoperand == "/")
        {
            answer = secone / sectwo;
        }
    }
    


  • Closed Accounts Posts: 4,943 ✭✭✭Mutant_Fruit


    This will probably work (i'm too lazy to compile and check it). Basically, if operand1 is multiply or divide, rules of maths say it should be done first. So i send the first two numbers and their operator to the "operate" function, which returns the answer. If that is not the case, just work out the second set (num2, num3 and operand2) first, then do the first set.

    This way you are guaranteed to work it out in the right mathematical order.
            var operate(var a, var b, var op)
            {
                switch (op)
                {
                    case("+"):
                        return (a + b);
                    case("-"):
                        return (a - b);
                    case("*"):
                        return (a * b);
                    case("/"):
                        return (a / b);
                }
            }
            private void main()
            {
                var num1 = 0;
                var num2 = 0;
                var num3 = 0;
                var operand1 = "";
                var operand2 = "";
                var spareoperand = "";
                var secone = "";
                var sectwo = "";
                var answer = 0;
                num1 = parseFloat(prompt("Please enter the first number ", ""));
                operand1 = prompt("Please enter the first mathematical operand " + "");
                num2 = parseFloat(prompt("Please enter the second number " + ""));
                operand2 = prompt("Please enter the second mathematical operand " + "");
                num3 = parseFloat(prompt("Please enter the third number " + ""));
    
                if (operand1 == "*" || operand1 == "/")
                {
                    answer = operate(num1, num2, operand1);
                    answer += operate(answer, num3, operand2);
                }
                else
                {
                    answer = operate(num2, num3, operand2);
                    answer += operate(num1, num2, operand1);
                }
    


  • Registered Users Posts: 919 ✭✭✭timeout


    Now that looks a hell of a lot neater then mine, completely forgot about switch, don't know why but i just thought it was used for integers.Oh well.

    [edit] now that i look at it a second time you don't have it in mathamatical order.
    If you get 9 / 3 * 3, under yours the 9 /3 will be done first rather then the 3*3


  • Closed Accounts Posts: 4,943 ✭✭✭Mutant_Fruit


    timeout wrote:
    now that i look at it a second time you don't have it in mathamatical order.
    If you get 9 / 3 * 3, under yours the 9 /3 will be done first rather then the 3*3
    Very good point :P I was thinking that multiplication and division were on the same level, so the order didn't matter. Thats obviously not right :P

    However, splitting out the actual calculating to a seperate function will reduce lines of code HUGELY, as you can see.

    Now, your task is to fix my code to make it work right :P


  • Advertisement
  • Registered Users Posts: 919 ✭✭✭timeout


    However, splitting out the actual calculating to a seperate function will reduce lines of code HUGELY, as you can see.
    Very true, it does look alot less bulky.
    Now, your task is to fix my code to make it work right :P
    Well its not my college assignment so i'll leave the op to sort it out ;)


  • Registered Users Posts: 1,275 ✭✭✭bpmurray


    Well, here's the eval solution:
    <html><head>
    </head><body>
    Input an expression: 
    <input id="foo" onblur="alert(eval(this.value));">
    </body></html>
    

    It's a little shorter than the full parser!


  • Registered Users Posts: 4,003 ✭✭✭rsynnott


    I'd be willing to bet that the lecturer has forgotten eval exists, and will be less than happy to see it turning up...

    That said, it's not a terribly difficult problem anyway.


  • Closed Accounts Posts: 2,046 ✭✭✭democrates


    For top marks present each alternative, and acknowledge the security risk of using eval like that (always wise to put on your hacker hat and attack your own system).


  • Closed Accounts Posts: 4,943 ✭✭✭Mutant_Fruit


    if you're going to use eval, put in a "hacker check" and make sure the string your eval'ing contains only three numbers and two operators. Or else anything could be evaluated!


  • Closed Accounts Posts: 169 ✭✭akari no ryu


            var operate(var a, var b, var op)
            {
                switch (op)
                {
                    case("+"):
                        return (a + b);
                    case("-"):
                        return (a - b);
                    case("*"):
                        return (a * b);
                    case("/"):
                        return (a / b);
                }
            }
            private void main()
            {
                var num1 = 0;
                var num2 = 0;
                var num3 = 0;
                var operand1 = "";
                var operand2 = "";
                var spareoperand = "";
                var secone = "";
                var sectwo = "";
                var answer = 0;
                num1 = parseFloat(prompt("Please enter the first number ", ""));
                operand1 = prompt("Please enter the first mathematical operand " + "");
                num2 = parseFloat(prompt("Please enter the second number " + ""));
                operand2 = prompt("Please enter the second mathematical operand " + "");
                num3 = parseFloat(prompt("Please enter the third number " + ""));
    
                if (operand1 == "*" || operand1 == "/")
                {
                    answer = operate(num1, num2, operand1);
                    answer += operate(answer, num3, operand2);
                }
                else
                {
                    answer = operate(num2, num3, operand2);
                    answer += operate(num1, num2, operand1);
                }
    
    Private void main in a javascript?


  • Closed Accounts Posts: 4,943 ✭✭✭Mutant_Fruit


    Private void main in a javascript?
    I'm a c# man at heart :p


  • Registered Users Posts: 18 suavek


    I was thinking that multiplication and division were on the same level, so the order didn't matter. Thats obviously not right :P

    It's kinda late so I might be missing something obvious, but last time I checked multiplication and division were on the same level, you just work them out from left to right...
    Wikipedia says so, too.
    That code doesn't work in math order for different reasons, see what happens with "10 - 3 + 3".

    [edit] ok, the logical part of my brain has kicked in for a second. Mutant_Fruit, you've never actually said multiplication and division were on different levels, have you? My English is playing me tricks this... morning.
    Anyway, the math order isn't preserved and the whole "answer+=" business is highly unconvincing ;)


  • Closed Accounts Posts: 13 ConnD3mned


    AAAAAAHHHHHHHHHH

    Alright I'm pretty sure that the code is will work out the bleedin' thing mathematically correct. One slight problem there seems to be an error in my code so it won't work (as in the prompts don't even pop up when I load up the web page). I think the error is in the getanswer function.

    Any help on this would be much appreciated.


  • Closed Accounts Posts: 13 ConnD3mned


    Sorry got it working.
    I had

    function get_answer(var number1,var number2,var op)

    It should have been

    function get_answer(number1,number2,op)

    Damn it way too used to C#.

    Thanks for all the help guys. I'm sure I'll be needing it again in the future.


  • Advertisement
  • Closed Accounts Posts: 2,046 ✭✭✭democrates


    function get_answer(number1, number2, op)
    VARicose function
    Edit: How did I miss your post? Swear to God everybody.


Advertisement