numbers I'm missingExample:
the array I pass is [1,5,6,9]
the numbers I'm missing are 2,3,4,7,8
the counter should be 5
what I'm attempting to do:
without using any built ins. while my next number in my list is not the next number already in my list I would increment by one.
function missing(numbers){
counter = 0;
let j = 1;
for(let i = 0; i<numbers.length; i++){
while(numbers[i+1] != numbers[i]+j){
j+=1;
counter+=1;
console.log("missing "+ numbers[i]+j)
}
}
return counter;
}
I'd suggest using a Set to contain all numbers in the input array, then generating a range array of all possible numbers corresponding to that array.
We do this by first getting the min and max of our input array, then generating the range from min to max.
Then we use Array.filter() to remove all items in the range array in our original array (in the Set)
function getMissingNumbers(arr) {
const [min,max] = [Math.min(...arr), Math.max(...arr)];
const range = Array.from({ length: (max - min + 1)}, (v,k) => k + min);
const nSet = new Set(arr);
return range.filter(n => !nSet.has(n));
}
console.log(getMissingNumbers([1,5,6,9]))
console.log(getMissingNumbers([1,5]))
console.log(getMissingNumbers([2,3,4,5,8,9]))
.as-console-wrapper { max-height: 100% !important; top: 0; }
And a slightly simpler version (assuming arrays are sorted):
function getMissingNumbers(arr) {
let s = new Set(arr);
let range = Array.from({ length: (arr[arr.length-1] - arr[0])}, (v,k) => k + arr[0]);
return range.filter(n => !s.has(n));
}
console.log(getMissingNumbers([1,5,6,9]))
console.log(getMissingNumbers([1,5]))
console.log(getMissingNumbers([2,3,4,5,8,9]))
.as-console-wrapper { max-height: 100% !important; top: 0; }
function missing(numbers){
counter = 0;
for(let i = 0; i<numbers.length; i++){
let j = 1;
while(numbers[i+1] != numbers[i]+j && numbers[i]+j < 10){
console.log(`missing + ${numbers[i]+j}`, numbers[i], j)
j+=1;
counter+=1;
}
}
return counter;
}
There are some issues with your logic.
You could take a single loop and run from index zero to the end of the given array.
At the same time use an variable for the increasing value and if not in the array push this value to the result set of missing values.
function getMissing(array) {
let i = 0,
v = array[0],
result = [];
while (i < array.length) {
if (v === array[i]) {
i++;
v++;
continue;
}
result.push(v++);
}
return result;
}
console.log(...getMissing([1, 5, 6, 9])); // 2 3 4 7 8