Skip to content

Instantly share code, notes, and snippets.

@XavierGeerinck
Created January 26, 2016 18:30
Show Gist options
  • Save XavierGeerinck/e9c36887fbda693ba219 to your computer and use it in GitHub Desktop.
Save XavierGeerinck/e9c36887fbda693ba219 to your computer and use it in GitHub Desktop.
Prefix Function Implemented Using Javascript (used in Knuth Morris Pratt, ...)
/**
* 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