0

I saw one interview question .(i.e)
I have one array inside a function

function validate(){
    var array=["(","{","[","]","}",")"];
 }

Also i have one input field with submit button

<body>
<input type="text" name="equation" id="equation">
<input type="submit" name="check" value="check" onclick="validate();">
</body>

Now my doubt is when I enter input data as {()} it should display valid data in an alert.When I enter input data like {()}] it should display as invalid data.Which means for unbalanced input it should display invalid message.For that I need to compare array elements within an array.

How to do it?

5
  • 1
    What did you try? Commented Jan 11, 2017 at 9:29
  • This it not clear. What should the function validate do ? What have you tried ? Commented Jan 11, 2017 at 9:31
  • ` var a=document.getElementById('equation').value; var y=eval(a); alert("your answer is"+y);` <br>i just tried using eval.But this is not my question i need compare array values only unbalanced symbols .I don't know how to do it. Commented Jan 11, 2017 at 9:33
  • is this only for braces or there can be other input as well? Commented Jan 11, 2017 at 9:40
  • @MustafaMamun we can give input like [(x+y)*(y-x)] but it should check only braces value doesn't matter. Commented Jan 11, 2017 at 9:47

1 Answer 1

1

You could save the opened brackets and delete the last if the corespondent bracket is found. At last, check if the open bracket array is empty.

function validate(s) {
    var open = [],
        brackets = { '(': 1, '{': 2, '[': 3, ']': -3, '}': -2, ')': -1 };

    return s.split('').every(function (a) {
        if (!brackets[a]) {
           return true;
        }
        if (brackets[a] > 0) {
            open.push(-brackets[a]);
            return true;
        }
        if (open[open.length - 1] ===  brackets[a] ) {
            open.pop();
            return true;
        }
    }) && open.length === 0;
 }

console.log(validate('([()()])'));
console.log(validate('(a+2)*4'));
console.log(validate(']'));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.