Last active
April 23, 2020 16:31
-
-
Save tanayv/16bd42665143fb69126470096190ffd8 to your computer and use it in GitHub Desktop.
Pattern Matching Problem
This file contains 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
/* Given a pattern and a string input - find if the string follows the same pattern and return 0 or 1. Examples: 1) Pattern : "abba", input: "redblueredblue" should return 1. 2) Pattern: "aaaa", input: "asdasdasdasd" should return 1. 3) Pattern: "aabb", input: "xyzabcxzyabc" should return 0. */ | |
const isMatch = (pat, str) => { | |
if (pat.length === 0 || str.len === 0) return false; | |
for (let i = 0; i <= str.length; i++) { | |
let activeStr = str.substring(0, i); | |
for (let j = i; j <= str.length; j++) { | |
for (let k = j; k <= str.length; k++) { | |
let subactiveStr = str.substring(j, k); | |
let genPattern = generatePattern(activeStr, subactiveStr, pat); | |
//console.log(genPattern); | |
if (genPattern === str) { | |
//console.log(`~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`); | |
//console.log(`Left: ${activeStr}, Right: ${subactiveStr}`); | |
return true; | |
} | |
} | |
} | |
} | |
return false; | |
} | |
const generatePattern = (left, right, pattern) => { | |
if (left === `` || right === ``) | |
return ``; | |
else { | |
console.log(`${left}:${right}`); | |
} | |
let result = ``; | |
let start = pattern[0]; | |
for (let c of pattern) { | |
if (c == start) | |
result += left; | |
else | |
result += right; | |
} | |
return result; | |
} | |
console.log(isMatch(`baba`, `redblueredblue`)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment