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
findMissingNumbersInSequence [Go Back]
Purpose
The purpose of this script is to find the missing numbers given a single-dimensional array (sorted or unsorted) of numbers. 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.

The Missing Numbers Question (and answer):
Print out the missing numbers from the array sequence: [1,2,4,5,7,19,9,12,16,8]
For reference, the missing numbers returned should be: [3,6,10,11,13,14,15,17,18]

Function Logic Output:


Full Working Code You Can Copy:
<html>
<head>
<script language="javascript" type="text/javascript">
function findMissingNumbersInSequence(sequence) {
	var missingSequence = [];
	/* Sort the sequence passed to this function */
	sequence.sort(function(a, b) {return a - b});
	/* Get the highest value in the sequence */
	var highestValue = 0;
	for (var x = 0; x < sequence.length; x++) {
		if (sequence[x] > highestValue) { highestValue = sequence[x]; }
	}
	/* Iterate through the array sequence that has missing numbers */
	var currentNumber = 1;
	for (var i = 0; i < sequence.length; i++) {
		var currentI = 0, nextI = 0;
		currentI = sequence[i];
		if ((i + 1) < sequence.length) { nextI = sequence[i + 1]; }
		if (nextI > 0) {
			if (currentI != currentNumber) {
				/* Iterate through the two known numbers from the sequence array to find the missing numbers */
				for (var y = currentI; y < (nextI - 1); y++) {
					var missingNumber = y + 1;
					currentNumber = missingNumber;
					/* Save missing number to the missingSequence array that will be returned */
					missingSequence.push(missingNumber);
				}
			}
		}
	}
	return(missingSequence);
}
</script>
</head>
<body onload='javascript:document.getElementById("output").value = findMissingNumbersInSequence([1,2,4,5,7,19,9,12,16,8]);'>
	Print out the missing numbers from the array sequence: [1,2,4,5,7,19,9,12,16,8]<br />
	<span style="font-size:9pt">For reference, the missing numbers returned should be: [3,6,10,11,13,14,15,17,18]</span>
	<br /><br />
	<strong>Function Logic Output:</strong><br />
	<textarea name="output" id="output" rows="4" cols="30"></textarea>
</body>
</html>
About Joe