Purpose
The purpose of this script is to find if an array sequence pattern is found within another array, in consecutive order. Fancy pants people may refer to this is as: given a set S determine if set X is a continguous sub-sequence of S. Over the decades of programming I've never needed to solve such a task but I was asked about it so I provide one approach (using javascript) below.
Determine if a Set is a Contiguous Sub-sequence of Another Set (and answer):
Given the base array *set* [5,15,-30,10,-5,40,10] is the array *set* [15,-30,10] a contiguous sub-sequence of the base array?
For reference, the value returned should be: true. Why? The sub-sequence [15,-30,10] is contiguous to the base array because the sub-sequence is found, consecutively, in that exact order.
Function Logic Output:
Full Working Code You Can Copy:
<html>
<head>
<script language="javascript" type="text/javascript">
function findContiguousSubset(sequenceA, sequenceB) {
var result = false;
var lastMatchingSubIndex = 0;
var lastIndex = -1, indexCount = 0;
for (var b = 0; b < sequenceA.length; b++) {
if (lastMatchingSubIndex < sequenceB.length) {
for (var s = lastMatchingSubIndex; s < sequenceB.length; s++) {
if (sequenceA[b] == sequenceB[s]) {
if (lastIndex == -1) {
lastIndex = b;
lastMatchingSubIndex = s;
indexCount = 1;
}
else {
if ((b - lastIndex) == 1) {
lastIndex = b;
lastMatchingSubIndex = s;
indexCount += 1;
if (indexCount == sequenceB.length) {
result = true;
break;
}
}
else {
lastIndex = -1;
lastMatchingSubIndex = 0;
indexCount = 0;
}
}
}
}
}
if (result == true) {
break;
}
}
return(result);
}
</script>
</head>
<body onload='javascript:document.getElementById("output").value = findContiguousSubset([5,15,-30,10,-5,40,10], [15,-30,10]);'>
Given the base array [5,15,-30,10,-5,40,10] is the array [15,-30,10] a contiguous sub-sequence of the base array?<br />
<span style="font-size:9pt">For reference, the value returned should be: true. Why? The sub-sequence [15,-30,10] is contiguous to the base array because the sub-sequence is found, consecutively, in that exact order.</span>
<br /><br />
<strong>Function Logic Output:</strong><br />
<textarea name="output" id="output" rows="4" cols="30"></textarea>
</body>
</html>