Main Page
 The gatekeeper of reality is
 quantified imagination.

Stay notified when site changes by adding your email address:

Your Email:

Bookmark and Share
Email Notification
findHeadAndShouldersInArray [Go Back]
Purpose
The purpose of this script is to find the head and shoulders pattern in an array, where the head value is the highest value in the array. 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.

Find the Head and Shoulders Question (and answer):
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).
For reference, the head and shoulders pattern returned should be: [15,18,9]

Function Logic Output:


Full Working Code You Can Copy:
<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>
About Joe