maxime
maxime

Reputation: 2315

Array position difference beetween two elements

I've got this array: [1,2,3,4,5]

I want to determine the position difference between two elements, but in a "rotation" mode.

Example: I have 3 and I want to know how far is 2, I do a 3.position - 2.position, and I've got 1.

But, if I have 5, and I want to know the position difference beetween 5.position and 1.position, with the precedent difference, I will have 5-1=4, and because there is array rotation, I want 1.

Do you have an idea of how I can do that ? (I work in Javascript)

EDIT: Here is a draw that can explain clearer what I want to do

EDIT 2: Better draw Draw circular

Upvotes: 0

Views: 265

Answers (2)

Alex Glover
Alex Glover

Reputation: 876

Guffa's answer is far more succinct and simple, but I already wrote the JSfiddle so I'll share.

var testArray = [1,2,3,4,5];

function getShortestDistance(element1Name, element2Name){
    var result = -1;
    var position1 = testArray.indexOf(element1Name);
    var position2 = testArray.indexOf(element2Name);
    // The distance should never be greater than half of the array length, half being defined as integer division by 2
    var maxDistance = Math.floor(testArray.length/2);
    if(Math.abs(position1 - position2) >= maxDistance){
        result = Math.abs(testArray.length - Math.abs(position1 - position2));
    }
    else{
        result = Math.abs(position1-position2);
    }
    alert('position1 is ' + position1);
    alert('position2 is ' + position2);
    alert('Distance is ' + result);
}

getShortestDistance(2,3); // Will return 1
getShortestDistance(1,4); // Will return 2

Here's the JSFiddle in case you want to modify it: http://jsfiddle.net/u71vbeau/16/

Upvotes: 0

Guffa
Guffa

Reputation: 700562

Calculate both the distance within the array, and the distance when wrapping around, and use the smallest.

This code uses pos1 and pos2 as the index of the items in the array arr, and assumes that pos1 < pos2:

var distance = Math.min(pos2 - pos1, pos1 + arr.length - pos2);

Upvotes: 3

Related Questions