Skip to content

Instantly share code, notes, and snippets.

@aire-con-gas
Created December 25, 2017 05:45
Show Gist options
  • Select an option

  • Save aire-con-gas/da9d4c492323cf2a00faf3cfb5c6117a to your computer and use it in GitHub Desktop.

Select an option

Save aire-con-gas/da9d4c492323cf2a00faf3cfb5c6117a to your computer and use it in GitHub Desktop.
regexMatching
function isMatch(text, pattern) {
var truthTable = [];
var textArr = text.split('');
var patternArr = pattern.split('');
function initRowArray() {
var newArr = [];
for(var i = 0; i <= patternArr.length + 1; i++) {
newArr[i] = null;
}
return newArr;
}
// Initialize truthTable
for(var i = 0; i <= textArr.length + 1; i++) {
truthTable.push(initRowArray());
}
// Set first pair to true where we handle
// a* or a*b*
truthTable[0][0] = true;
for(var i = 1; i < truthTable.length; i++) {
for(var j = 1; j < truthTable[0].length; j++) {
if(patternArr[j-1] === '.' || patternArr[j-1] === textArr[i-1]) {
truthTable[i][j] = truthTable[i-1][j-1];
} else if(pattern[j-1] === '*') {
truthTable[i][j] = truthTable[i][j-2];
if(patternArr[j-2] === '.' || patternArr[j-2] === textArr[i-1]) {
truthTable[i][j] = truthTable[i][j] || truthTable[i-1][j];
}
} else {
truthTable[i][j] = false;
}
}
}
console.log('*****');
console.log(truthTable);
return truthTable[textArr.length][patternArr.length];
}
console.log("isMatch", isMatch('a', 'a*'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment