Wednesday, March 15, 2023

Coding Challenge #22

 // 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

No comments:

Post a Comment

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 ...