Created
April 15, 2020 21:27
-
-
Save MeyCry/30579e36f17930d06387112a0c36690f to your computer and use it in GitHub Desktop.
validate brackets and merge sorted arrays.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
// 1 | |
function smartJoin(arrA, arrB) { | |
let aIndex = 0; | |
let bIndex = 0; | |
const result = []; | |
while (aIndex < arrA.length || bIndex < arrB.length) { | |
const itemA = arrA[aIndex]; | |
const itemB = arrB[bIndex]; | |
if ( | |
itemA < itemB | |
|| (bIndex >= arrB.length && aIndex < arrA.length) | |
) { | |
result.push(itemA); | |
aIndex++; | |
continue; | |
} | |
if ( | |
itemA >= itemB | |
|| (aIndex >= arrA.length && bIndex < arrB.length) | |
) { | |
result.push(itemB); | |
bIndex++; | |
continue; | |
} | |
console.error("Something go wrong..."); | |
break; | |
} | |
return result; | |
} | |
const a = [4, 6, 10, 15]; | |
const b = [1, 5, 7, 12, 20]; | |
console.log(smartJoin(a, b)); | |
const a1 = [30, 31, 100]; | |
const b1 = [1, 3, 4, 5, 6, 7, 8, 9]; | |
console.log(smartJoin(a1, b1)); | |
const a2 = [1, 3, 4, 5, 6]; | |
const b2 = [20, 30, 40, 50, 60, 90, 100]; | |
console.log(smartJoin(a2, b2)); | |
const a3 = [1, 3, NaN]; | |
const b3 = [2, 4, 5]; | |
console.log(smartJoin(a3, b3)); | |
})(); | |
(function() { | |
// 2 | |
function validate(str) { | |
const arrStr = str.split(""); | |
const validSymbols = { | |
"(": ")", | |
"{": "}", | |
"[": "]", | |
}; | |
let stack = []; | |
arrStr.forEach((letter) => { | |
if (["(", "{", "[", "]", "}", ")"].includes(letter)) { | |
if (["(", "{", "["].includes(letter)) { | |
stack.push(letter); | |
} else { | |
const last = stack.pop(); | |
if (validSymbols[last] !== letter) { | |
throw new Error("invalid: " + str); | |
} | |
} | |
} | |
}); | |
if (stack.length !== 0) { | |
throw new Error("!invalid: " + str); | |
} | |
return `valid: ${str}` | |
} | |
console.log(validate("()")); | |
console.log(validate("ab(cd()ef)g")); | |
console.log(validate("[{()}]")); | |
try { | |
validate(")("); | |
} catch (e) { | |
console.log(e.message); | |
} | |
try { | |
validate("a)b(cd()ef)g"); | |
} catch (e) { | |
console.log(e.message); | |
} | |
try { | |
validate("ab(cd()ef)g)"); | |
} catch (e) { | |
console.log(e.message); | |
} | |
try { | |
validate("{ab(cd()ef)g)"); | |
} catch (e) { | |
console.log(e.message); | |
} | |
try { | |
validate("[({)}]"); | |
} catch (e) { | |
console.log(e.message); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment