2

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?

0

1 Answer 1

2

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.

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.