Arrays - Find missing numbers in a Sequence

后端 未结 15 1443
小鲜肉
小鲜肉 2021-02-01 04:08

I\'m trying to find an easy way to loop (iterate) over an array to find all the missing numbers in a sequence, the array will look a bit like the one below.

var nu

15条回答
  •  情话喂你
    2021-02-01 04:49

    I use a recursive function for this.

    function findMissing(arr, start, stop) {
    
        var current = start,
            next = stop,
            collector = new Array();
    
        function parseMissing(a, key) {
            if(key+1 == a.length) return;
    
            current = a[key];
            next = a[key + 1];
    
            if(next - current !== 1) {
                collector.push(current + 1);
                // insert current+1 at key+1
                a = a.slice( 0, key+1 ).concat( current+1 ).concat( a.slice( key +1 ) );
                return parseMissing(a, key+1);
            }
    
            return parseMissing(a, key+1);
        }
    
        parseMissing(arr, 0);
        return collector;
    }
    

    Not the best idea if you are looking through a huge set of numbers. FAIR WARNING: recursive functions are resource intensive (pointers and stuff) and this might give you unexpected results if you are working with huge numbers. You can see the jsfiddle. This also assumes you have the array sorted.

    Basically, you pass the "findMissing()" function the array you want to use, the starting number and stopping number and let it go from there.

    So:

    var missingArr = findMissing(sequenceArr, 1, 10);
    

提交回复
热议问题