uday8486
uday8486

Reputation: 1393

Javascript circular array find next element

I have a array of n elements. I am at a given position say x and I need to move to position y, I need to find out what is the difference or number of steps if I traverse array by going forward and by going backward.

const foo = Array.from(Array(15).keys());
const length = foo.length;
const currentItem = 2;
const next = 12;
let diff = currentItem - next;
if (diff < 0) {
  if (next > currentItem) {
    diff = next - currentItem;
    console.log((diff));
  } else {
    diff = length - Math.abs(diff);
    console.log(-diff);
  }
} else {
  if (next < currentItem) {
    console.log(-(diff));
  } else {
    console.log(diff);
  }
}

I am trying to fin in above code if I need to move forward or backward. In above example I expect answer as -6 but I get answer 10. I am getting bit confused in the loops. Any better and smarter way to do this?

Upvotes: 2

Views: 829

Answers (1)

Aadit M Shah
Aadit M Shah

Reputation: 74204

Here is how I'd do it:

// The % operator in JavaScript is the remainder operator.
// The following function defines the modulo operator.
const mod = (x, y) => (x % y + y) % y;

// Law: mod(start + shortestPath(start, end, length), length) === end
const shortestPath = (start, end, length) => {
    const forward  = mod(end - start, length);
    const backward = mod(start - end, length);
    return forward > backward ? -backward : forward;
};

const shortestPathLaw = (start, end, length) =>
    mod(start + shortestPath(start, end, length), length) === end;

console.assert(shortestPathLaw(4, 6, 10));
console.assert(shortestPathLaw(8, 6, 10));

console.log(shortestPath(4, 6, 10)); // 2
console.log(shortestPath(8, 6, 10)); // -2

We use the modulo operator to calculate the forward distance from point A to point B (i.e. B - A). The backward distance from point A to point B is the same as the forward distance from point B to point A (i.e. A - B). Then we pick the shorter of the two distances, and if the distance we picked is the backward distance, then we negate it to show that we're traveling backward from A to reach B.

Upvotes: 2

Related Questions