Javascript: Check If An Array Is A Subsequence Of Another Array (write A Faster Naïve String Search Algo)
[5, 4, 4, 6].indexOfArray([4, 6]) // 2 ['foo', 'bar', 'baz'].indexOfArray(['foo', 'baz']) // -1 I came up with this: Array.prototype.indexOfArray = function(array) { var m = a
Solution 1:
The algorithm you want is the KMP algorithm (http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm) used to find the starting index of a substring within a string -- you can do exactly the same thing for an array.
I couldn't find a javascript implementation, but here are implementations in other languages http://en.wikibooks.org/wiki/Algorithm_implementation/String_searching/Knuth-Morris-Pratt_pattern_matcher -- it shouldn't be hard to convert one to js.
Post a Comment for "Javascript: Check If An Array Is A Subsequence Of Another Array (write A Faster Naïve String Search Algo)"