<html>
<head>
<script language="javascript" type="text/javascript">
function findHeadAndShouldersInArray(sequence) {
var headAndShoulders = [];
/* Find the head (highest) value and its index */
var headValue = 0, headIndex = 0;
for (var h = 0; h < sequence.length; h++) {
if (sequence[h] >= headValue) {
headValue = sequence[h];
headIndex = h;
}
}
/* Find the shoulders (left, right) value and their indexes */
var leftShoulderValue = -1, rightShoulderValue = -1;
if ((headIndex - 1) >= 0) {
leftShoulderValue = sequence[(headIndex - 1)];
}
if ((headIndex + 1) <= (sequence.length - 1)) {
rightShoulderValue = sequence[(headIndex + 1)];
}
/* Save head and shoulders values */
headAndShoulders.push(leftShoulderValue);
headAndShoulders.push(headValue);
headAndShoulders.push(rightShoulderValue);
/* Alert if there is not a complete head and shoulders pattern, for example if no shoulder could be found. Missing shoulder will have value of -1. */
if (leftShoulderValue == -1 || rightShoulderValue == -1) {
window.alert("Head and shoulders sequence not found. Incomplete data represented by a value of -1.");
}
return(headAndShoulders);
}
</script>
</head>
<body onload='javascript:document.getElementById("output").value = findHeadAndShouldersInArray([1,2,15,18,9,7,6]);'>
Given the array sequence: [1,2,15,18,9,7,6] find the head and shoulders (that is: highest value, the value to the left and the value to the right).<br />
<span style="font-size:9pt">For reference, the head and shoulders pattern returned should be: [15,18,9]</span>
<br /><br />
<strong>Function Logic Output:</strong><br />
<textarea name="output" id="output" rows="4" cols="30"></textarea>
</body>
</html>