Home > other >  Printing missing numbers
Printing missing numbers

Time:11-14

So I have a question with regards to printing out missing numbers.

I have an array of integers ranging from 0 - 20 and should return a string of missing numbers.

e.g.

[0, 1, 2, 8, 12, 13] would return "3-7,9-11,14-20"

[1, 2, 5, 12, 16] would return "0,3-4,6-11,13-15,17-20"

I'm just having trouble printing out the missing values as a sequence.

Here is my code so far:

function missingNumbers(arr){
    let count = 20;
    let missing = new Array();

    for(let i = 0; i <= count; i  ){
        if(arr.indexOf(i) === -1){
            missing.push(i);
        }
    }
    return missing.toString();
}

console.log(missingNumbers([1,2]))

CodePudding user response:

Compare each array element a[i] with a steadily growing counter of integers.

  • if a[i] matches, go to the next array element
  • otherwise, if a[i-1] matched, start a new "missing" range
  • otherwise, extend the current "missing" range

// [0, 1, 2, 8, 12, 13] would return "3-7,9-11,14-20"


function test(a) {
let missing = [];

for (let curr = a[0], i = 0; i < a.length; curr  ) {
    if (a[i] === curr) {
        i  
    } else if (a[i - 1] === curr - 1) {
        missing.push([curr, curr])
    } else {
        missing[missing.length - 1][1] = curr
    }
}

return missing
}


console.log(test([0, 1, 2, 8, 12, 13]))

Printing ranges left as an exercise.

CodePudding user response:

const missingNumbers = (arr = []) => {
    let s = null;
    const missing = new Array(21).fill("").reduce((p, _, i) => {
        if (!arr.some(a => a === i) && s === null) s = i;
        if (arr.some(a => a === i) && s !== null) {
            s === (i - 1) ? p.push(s) : p.push(`${s}-${i-1}`);
            s = null;
        }
        return p;
    }, []);
    if (Math.max(...arr)!==20) missing.push(`${Math.max(...arr) 1}-20`);

    return missing;
}

console.log(missingNumbers([1, 2]));
console.log(missingNumbers([0, 1, 2, 8, 12, 13]));
console.log(missingNumbers([1, 2, 5, 12, 16]));

  • Related