Skip to content

Instantly share code, notes, and snippets.

@ShilpiMaurya
Last active October 24, 2020 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShilpiMaurya/0441f44f8e770a4e5fb9667c80060a39 to your computer and use it in GitHub Desktop.
Save ShilpiMaurya/0441f44f8e770a4e5fb9667c80060a39 to your computer and use it in GitHub Desktop.
//Weekly challenge
//Bracket Matcher
//Have the function BracketMatcher(str) take the str parameter being passed
//and return 1 if the brackets are correctly matched and each one is accounted
//for. Otherwise return 0. For example: if str is "(hello (world))",
//then the output should be 1, but if str is "((hello (world))" the
//the output should be 0 because the brackets do not correctly match up.
//Only "(" and ")" will be used as brackets. If str contains no brackets
//return 1.
//Examples
//Input: "(coder)(byte))"
//Output: 0
//Input: "(c(oder)) b(yte)"
//Output: 1
//hint:
//1. First should be opening bracket
//2. All brackets should be close
const bracketMatcher = str => {
const openingBracket = "(";
const closingBracket = ")";
let counter = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] === openingBracket) {
counter = counter + 1;
} else if (str[i] === closingBracket) {
counter = counter - 1;
}
}
return counter;
};
console.log(bracketMatcher("h(el)lo)wor(ld"));
//OLD AlGO
// opening and closing brackets count should be equal
// first bracket in the string should always be opening and last should always be closing
//New Algo
//For every closed bracket there should be a opening bracket
//No of opening and closing bracket should be same.
// asdfds(sdfd)s)
// asdf(sdf))(())
/// asd())(()
//tests
const testCases = [
{
input: "(coder)(byte))",
output: false
},
{
input: "(c(oder)) b(yte)",
output: true
},
{
input: "hello world",
output: true
},
{
input: "sh)il(pi",
output: false
},
{
input: "s((h)(ilpi",
output: false
},
{
input: "shilpi)",
output: false
},
{
input: "sh(ilpi",
output: false
},
{
input: "asd())(()",
output: false
}
];
testCases.forEach(({ input, output }, idx) => {
console.log(
`Test case ${idx} (${input}): ${
bracketMatcher(input) === output ? "successs" : "failure"
}`
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment