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.
-
5Some example code and a programming language would be useful, you're essentially just asking us to write your codeDanny Wilson– Danny Wilson11/25/2016 13:40:58Commented Nov 25, 2016 at 13:40
3 Answers 3
If the array is not sorted, sort it, then look for an increase of more than 1 in neighbor elements.
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
-
I really like the id of getting max and min. You can just substract them and check against the array length to find out, how many are missing.Seb– Seb11/25/2016 14:26:02Commented Nov 25, 2016 at 14:26
-
You need to check that the array doesn't have duplicates, and only contains integers. Otherwise
3,3,5
and3,3.1,5
will matchEric Duminil– Eric Duminil11/25/2016 14:56:42Commented Nov 25, 2016 at 14:56
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.