javascript - all valid combinations of n-pair of parenthesis -


  • i learning js now..
    • i trying write simple js programme..
    • what trying print valid combinations of n-pair of parenthesis(properly opened , closed)
    • eg (), (()()),(())
    • i have written logic can tell me whether correct or not

https://jsfiddle.net/e7mcp6xb/

module.exports = parentheses = (function() {   var _isparenthesesmatch = function(str) {     var parentheses = str.length;     var rightparentheses = '(';     var leftparentheses = ')';     var rightcount = 0;     var leftcount = 0;      for(i=0;i<=str.length;i++){        if(rightparentheses == str.charat(i))        {           rightcount++;        }        else if(leftparentheses == str.charat(i))        {           leftcount++;        }     }      if(rightcount == leftcount){       return true;     }     else(rightcount != leftcount){       return false;     }    }  }()); 

the check wrong, can fix easily: in each step of for loop number of opening parenthesis cannot smaller number of closing ones:

if (rightcount < leftcount)     return false; 

the whole function should this:

function(str) {     var rightparentheses = '(';     var leftparentheses = ')';     var rightcount = 0;     var leftcount = 0;      (var = 0; <= str.length; i++) {        if (rightparentheses == str.charat(i))           rightcount++;        else if (leftparentheses == str.charat(i))           leftcount++;         if (rightcount < leftcount)           return false;     }      return rightcount == leftcount; } 

if you'd generate valid strings, can use function:

function npair(n) {     if (n == 0)         return [""];      var result = [];     (var = 0; < n; ++i) {          var lefts = npair(i);         var rights = npair(n - - 1);          (var l = 0; l < lefts.length; ++l)             (var r = 0; r < rights.length; ++r)                 result.push("(" + lefts[l] + ")" + rights[r]);     }      return result; }  // result of npair(3): // ["()()()", "()(())", "(())()", "(()())", "((()))"] 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -