3

Given an array of unsorted positive ints, write a function that finds runs of 3 consecutive numbers (ascending or descending) and returns the indices where such runs begin. If no such runs are found, return null.

function findConsecutiveRuns(input:Array):Array

Example: [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7] would return [0, 4, 6, 7]

My JS skills are a bit rusty, here is my attempt at this...

var numArray = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7];
var newNumArray = []; 

for(var i = 1; i < numArray.length; i++) {
    if ((numArray[i] - numArray[i-1] != 1) || (numArray[i] + numArray[i+1] !=1)  {
        return 0;
    }
    else {
    newNumArray.push(numArray[i]);
    }
}
alert(newNumArray);
0

1 Answer 1

5

Here:

function f ( arr ) {
    var diff1, diff2, result = [];

    for ( var i = 0, len = arr.length; i < len - 2; i += 1 ) {
        diff1 = arr[i] - arr[i+1];
        diff2 = arr[i+1] - arr[i+2];
        if ( Math.abs( diff1 ) === 1 && diff1 === diff2 ) {
            result.push( i );
        }        
    }

    return result.length > 0 ? result : null;
}

Live demo: http://jsfiddle.net/Cc4DT/1/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.