Skip to content

Instantly share code, notes, and snippets.

@sccheruku
Created January 6, 2016 14:52
Show Gist options
  • Save sccheruku/bb11efeb33b3470f25af to your computer and use it in GitHub Desktop.
Save sccheruku/bb11efeb33b3470f25af to your computer and use it in GitHub Desktop.
Finds the missing number in a list
//Find the missing number in a list
//http://stackoverflow.com/questions/2113795/quickest-way-to-find-missing-number-in-an-array-of-numbers
//list can start anywhere, assumes arithmetric series where n, n+1,n+2 etc..
function getMissingNum() {
var start = Math.floor(Math.random() * 150) / 1;
var nElem = Math.floor(Math.random() * 20) / 1;
var set = [];
var rand = Math.floor(Math.random() * nElem) + start / 1;
for (var i = start; i <= start + nElem; i++) {
//skip one number randomly
if (i == rand) continue;
set.push(i);
}
var sum = 0;
for (var i = 0; i < set.length; i++) {
sum += set[i];
}
// Total = N * (N + 1) / 2
var max = set[set.length - 1];
var min = set[0];// - 1;
var actual = (((max * (max + 1)) / 2));
var excluded = (((min * (min + 1)) / 2));
var missing = actual - excluded - sum + start;
if (min > start) {
missing = missing + min;
}
return {
missing: missing,
min: min,
max: max,
actual: actual,
excluded: excluded,
rand: rand,
start: start,
nElem: nElem
}
}
var results = [];
for (var i = 0; i < 100; i++) {
var result = getMissingNum();
if (result.rand != result.missing) {
results.push(result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment