Code Challenge: Consecutive

Each week, I offer up a JavaScript code challenge. Want more? You can find others here.

This week’s code challenge comes again from Coderbyte:

Using the JavaScript language, have the function Consecutive(arr) take the array of integers stored in arr and return the minimum number of integers needed to make the contents of arr consecutive from the lowest number to the highest number. For example: If arr contains [4, 8, 6] then the output should be 2 because two numbers need to be added to the array (5 and 7) to make it a consecutive array of numbers from 4 to 8. Negative numbers may be entered as parameters and no array will have less than 2 elements.

Here are some provided test cases:

Input = 5,10,15 Output = 8
Input = -2,10,4 Output = 10

Here is my solution collapsed:

function Consecutive(arr) { 
    var highest = arr[0];
    var lowest = arr[0];
    var numbersBetween = [];

    for (var i = 0; i<arr.length; i++) {
        if (arr[i] > highest) {
            highest = arr[i];
        } else if (arr[i] < lowest) {
            lowest = arr[i];
        };
    };

    for (var j = lowest; j<=highest; j++) {
        if (arr.indexOf(j) == -1) {
            numbersBetween.push(j);
        };
    };
    
    return numbersBetween.length; 
};

The first step was to figure out the highest and lowest numbers in the array so I could start working on creating a consecutive array of numbers between them. I created two variables, highest and lowest. Both were set to the first array item in the beginning. Then, I looped over the array and set the highest and lowest accordingly:

for (var i = 0; i<arr.length; i++) {
    if (arr[i] > highest) {
        highest = arr[i];
    } else if (arr[i] < lowest) {
        lowest = arr[i];
    };
};

Now, I just needed to create a new array between the highest and lowest numbers. To do that, I created another for loop. I started at the lowest number and worked up to the highest in increments of one. I used indexOf() to find out whether or not the number was in the original array. If it was not in the array already (indexOf() returned -1), I pushed it onto a new array I called numbersBetween. Then, I could just return the length of numbersBetween.

Alternatively, I could have just setup a counter variable that was incremented. I setup the new array mainly because I was interested in logging out the array for testing/fun.

for (var j = lowest; j<=highest; j++) {
    if (arr.indexOf(j) == -1) {
        numbersBetween.push(j);
    };
};
Categories: Code