Created
January 26, 2016 18:30
-
-
Save XavierGeerinck/e9c36887fbda693ba219 to your computer and use it in GitHub Desktop.
Prefix Function Implemented Using Javascript (used in Knuth Morris Pratt, ...)
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
/** | |
* We start by setting element [0] on 0 | |
* Check every time of the index of arr found by getting prefix[i] is the same, | |
* if so do +1 else start over from 0 | |
**/ | |
function calculate_prefix(patternArr) { | |
var prefix = []; | |
// First index is 0 | |
prefix[0] = 0; | |
// Calculate the prefix | |
for (var i = 1; i < arr.length; i++) { | |
if (arr[prefix[i - 1]] == arr[i]) { | |
prefix[i] = prefix[i - 1] + 1; | |
} else { | |
prefix[i] = 0; | |
} | |
} | |
return prefix; | |
} | |
var arr = ['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'c', 'a']; | |
console.log(calculate_prefix(arr)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment