Reputation: 11
An array is given :array(1,2,3,4,6,8,9). Here 2 numbers are missing. My question is how to find , if more than 1 numbers are missing.
Upvotes: 1
Views: 81
Reputation: 7291
In Javascript (the principles should carry over), you can sort it numerically then work your way through the array looking for numbers that aren't there. When you find them you can make a note of it a and move on.
Have a look here:
var numberArray = [1, 2, 3, 4, 6, 8, 9, 15, 12];
var missingArray = [];
function findMissing() {
var sortedArray = numberArray.sort(function(a, b) {
return a - b
});
var currentNo = sortedArray[0];
for (let i = 0; i < sortedArray.length; i++) {
if (sortedArray[i] == currentNo) {
currentNo++
} else {
missingArray.push(currentNo);
i--;
currentNo++;
}
}
document.querySelector(".problem").innerHTML = "Array numbers are " + numberArray;
document.querySelector(".result").innerHTML = "Missing numbers are " + missingArray;
}
findMissing();
<div class="problem"></div>
<div class="result"></div>
Hope this helps.
Upvotes: 0
Reputation: 54293
You could extract min and max, and compare array to the range from min and max.
Ruby example :
array = [1,2,3,4,6,8,9]
min, max = array.minmax
missing = (min..max).to_a - array
#=> [5,7]
or sort and look for gaps that are bigger than 1
array = [1,2,3,4,6,8,9,12]
array.sort.each_cons(2) do |a,b|
if (b-1) > a then
(a+1..b-1).each do |i|
puts "#{i} is missing"
end
end
end
# 5 is missing
# 7 is missing
# 10 is missing
# 11 is missing
Upvotes: 1
Reputation: 12057
If the array is not sorted, sort it, then look for an increase of more than 1 in neighbor elements.
Upvotes: 3