Skip to content

Instantly share code, notes, and snippets.

@jinwolf
Created February 29, 2016 05:21
Show Gist options
  • Select an option

  • Save jinwolf/7982c9877f721f61943b to your computer and use it in GitHub Desktop.

Select an option

Save jinwolf/7982c9877f721f61943b to your computer and use it in GitHub Desktop.
Finding a repeated number using pigeon hole principle
'use strict'
// pigeon hole theory
// number range 1 - n
// array length n + 1
const num_list = [10, 2, 4, 3, 2, 5, 6, 9, 8, 7, 1];
const num_list2 = [10, 2, 4, 3, 5, 6, 9, 8, 7, 1, 8];
function findDuplicate(num_list) {
var floor = 1;
var ceiling = num_list.length - 1;
while(floor < ceiling) {
let actualItemCount = 0;
let midPoint = Math.floor((ceiling - floor) / 2) + floor;
let lowFloor = floor;
let lowCeiling = midPoint;
let highFloor = midPoint + 1;
let highCeiling = ceiling;
num_list.forEach(function(item) {
if (item >= lowFloor && item <= lowCeiling) {
actualItemCount++;
}
});
let distinctPossibilities = lowCeiling - lowFloor + 1;
if (actualItemCount > distinctPossibilities) {
// update the bound
floor = lowFloor;
ceiling = lowCeiling;
} else {
// update the bound
floor = highFloor;
ceiling = highCeiling;
}
}
return floor;
}
console.log(findDuplicate(num_list));
console.log(findDuplicate(num_list2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment