Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mistake in test case Question #230 #331

Open
Eghizio opened this issue Jun 21, 2021 · 0 comments
Open

Mistake in test case Question #230 #331

Eghizio opened this issue Jun 21, 2021 · 0 comments

Comments

@Eghizio
Copy link

Eghizio commented Jun 21, 2021

There is a mistake in this question.

image

It is written that "{dklf(df(kl))d]{}" is a valid test case while it is not due to the not opened "[".

Please update the question.

The code I used to test the cases:

const sum = (arr: number[]): number => arr.reduce((acc, el) => acc+el, 0);

type OpeningBracket = "(" | "[" | "{";
type BracketStackMap = Record<OpeningBracket, number>;

const checkBrackets = (str: string) => {
  const brackets = ["(",")", "[","]", "{","}"]; // "()[]{}".split("");
  
  const filtered = str.split("").filter(character => brackets.includes(character));
  const bracketsStack = new Map<BracketStackMap>([["(", 0], ["[", 0], ["{", 0]]);

  for(let i=0; i<filtered.length; i++){
    // could be simplified with closed/opening bracket key/value mapping
    const key = filtered[i] === ")" ? "("
          : filtered[i] === "]" ? "["
          : filtered[i] === "}" ? "{"
          : filtered[i];
    
    const currentVal = bracketsStack.get(key);
    
    // console.log({i, str: filtered[i], key})
    
    switch(filtered[i]){
      case "(":
      case "[":
      case "{":
        bracketsStack.set(filtered[i], currentVal + 1);
        break;
      case ")":
      case "]":
      case "}":
        bracketsStack.set(key, currentVal - 1);
        break;
      default: throw new Error(`Unhandled bracket: ${filtered[i]}`);
    }
    
    if(bracketsStack.get(key) < 0){
      // console.log("negative", bracketsStack.get(key))
      return false;
    };
  }
  
  return (sum([...bracketsStack.values()]) === 0);
};

const tests = {
  "{ac[bb]}": true, 
  "{dklf(df(kl))d]{}": true, //fails, should pass according to task description
  "{[[[]]]}": true,
  "{3234[fd": false,
  "{df][d}": false
};

Object.entries(tests).forEach(([test, expected]) => {
  const result = (checkBrackets(test) === expected) ? "✅" : "❌";
  
  console.log(`${result} "${test}" `);
});
// results
"✅ '{ac[bb]}' "
"❌ '{dklf(df(kl))d]{}' "
"✅ '{[[[]]]}' "
"✅ '{3234[fd' "
"✅ '{df][d}' "
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant