// Daily Coding Challenge #27
// Determine whether a string of (), [], and {} are properly formatted (enough to match each other, are closed in LOFO order of having been added).
// Return true if it is properly formatted. Return false if it is not.
closerFor = {')':'(',
'}':'{',
']':'['};
function judge(str){
var stack = [];
for(var xint = 0, len = str.length;xint < len;xint++){
var c = str.charAt(xint);
if(c == '(' || c == '{' || c == '[') stack.push(c); // new phrase
else if(c == ')' || c == '}' || c == ']'){ // try to close phrase
console.log('trying close; xint = ' + xint + ', c = ' + c + ', stack len: ' + stack.length + ', stack: ' + stack.toString());
if(stack.length == 0 || stack[stack.length-1] != closerFor[c]) return false; // incorrect format
else stack.splice(stack.length-1,1); // successfully closed phrase; pop the back off, LOFO
}
}
console.log('stack len: ' + stack.length);
if(stack.length == 0) return true; // no phrases left unfinished
else return false;
}
// tests (PASS means the algorithm works. FAIL means the expected result was not reached)
if(judge("{[{[()]}]}")) console.log("Algorithm PASS"); else console.log("Algorithm FAIL"); // should be true
if(!judge("{[]}]}")) console.log("Algorithm PASS"); else console.log("Algorithm FAIL"); // should be false
if(judge("[][](){}")) console.log("Algorithm PASS"); else console.log("Algorithm FAIL"); // should be true
if(!judge("(")) console.log("Algorithm PASS"); else console.log("Algorithm FAIL"); // should be false
Wednesday, March 15, 2023
Coding Challenge #22
Subscribe to:
Post Comments (Atom)
Coding Challenge #54 C++ int to std::string (no stringstream or to_string())
Gets a string from an integer (ejemplo gratis: 123 -> "123") Wanted to come up with my own function for this like 10 years ago ...
-
I NEEDS MY JAVASCRIPT PLEASE :) Open txtcode .txt Save as .gct Please click the blue cheat code title to activate it, a...
-
Naruto Personality Quiz Please enable javascript ☯ Which Naruto Character Are You?
-
Useful for extensions that want to prevent event listeners from being attached or modify prototypes or functions, generally to defeat click...
No comments:
Post a Comment