Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding the biggest difference between sorted array values

I have an array that may look like this...

var array = array(1,4,7,8,12,15);

The values in the array will always be integers, and always will go up, or could be the same as the previous, but at least won't become less.

Now i would like to loop through the array and find out which "step" has the biggest difference between it, so in my example that would be array keys 4&5 since from 8-12 == 4... but it might also happen that this would be multiple steps with the same values, let's say my array would be this..

var array = array(1,5,7,8,12,15);

then it would be 0&1 and 4&5....

I'm looking for a function that can return me this... oh and it has to be PureJs...

I hope someone can help me.

like image 620
Tobias Hagenbeek Avatar asked Mar 23 '23 12:03

Tobias Hagenbeek


1 Answers

I'm not sure exactly what you want. But if you want the greatest jump:

var max=0;
for (i=1; i<array.length; i++)
    max = Math.max(max,array[i]-array[i-1]);

If you want the first location at which this greatest jump occurs:

var max=0;
var firstLoc=0;
for (i=1; i<array.length; i++)
{
    curJump = array[i]-array[i-1];
    if (curJump > max) 
    {
        firstLoc = i;
        max = curJump;
    }
}

If you want the last location at which this jump occurs:

var max=0;
var lastLoc=0;
for (i=1; i<array.length; i++)
{
    curJump = array[i]-array[i-1];
    if (curJump >= max) 
    {
        lastLoc = i;
        max = curJump;
    }
}

If you want an array of all locations at which this max jump occurs:

var max=0;
var locs = [];
for (i=1; i<array.length; i++)
{
    curJump = array[i]-array[i-1];
    if (curJump == max)
    {
        locs.push(i);
    } else if (curJump > max)
    {
        locs = [i];
        max = curJump;
    }
}
like image 167
galdre Avatar answered Apr 06 '23 06:04

galdre