3
\$\begingroup\$

The task is taken from leetcode

There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.

The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), and D (down). If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false.

Note: The way that the robot is "facing" is irrelevant. "R" will always make the robot move to the right once, "L" will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.

Example 1:

Input: "UD" Output: true Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.

Example 2:

Input: "LL" Output: false Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.

const arr = "UD";

My imperative solution:

function judgeCircle(moves) {
  let horizontal = 0;
  let vertical = 0;

  [...moves].forEach(m => {
    switch(m) {
      case "U":
        ++vertical;
        break;
      case "D":
        --vertical;
        break;
      case "R":
        ++horizontal;
        break;
      case "L":
        --horizontal;
        break;
      default:
        // be a good code
    }
  });
  return !(horizontal) && !(vertical);
};

console.log(judgeCircle(arr));

My functional solution:

const judgeCircle2 = moves => {
  const {h, v} = [...moves].reduce((acc,m) => {
    switch(m) {
      case "U":
        ++acc.v;
        return acc;
      case "D":
        --acc.v;
        return acc;
      case "R":
        ++acc.h;
        return acc;
      case "L":
        --acc.h;
        return acc;
      default:
        // be a good code
    }
  }, {h: 0, v: 0});
  return !h && !v;
};

console.log(judgeCircle2(arr));
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

You can often replace switch statements with lookup functions. For example

function returnsHome(moves) {
    var v = 0, h = 0;
    const dirs = { 
        U() {v++}, 
        D() {v--}, 
        L() {h--}, 
        R() {h++} 
    };
    for (const move of moves) { dirs[move]() }
    return !(h || v);
}

// or
function returnsHome(moves) {
    var v = 0, h = 0;
    const dirs = {U() {v++}, D() {v--}, L() {h--}, R() {h++}};
    for (const m of moves) { dirs[m]() }
    return !(h || v);
}

There is also a very quick way to workout if the result is false by checking if the number of moves is odd.

function returnsHome(moves) {
    var v = 0, h = 0;
    if (moves.length % 2) { return false }        
    const dirs = {U() {v++}, D() {v--}, L() {h--}, R() {h++}};
    for (const m of moves) { dirs[m]() }
    return !(h || v);
}

Another early exit can be found if a particular distance moved if greater than the remaining number of moves.

function returnsHome(moves) {
    var v = 0, h = 0, remainingSteps = moves.length;
    if (remainingSteps % 2) { return false }
    const dirs = {U() {v++}, D() {v--}, L() {h--}, R() {h++}};
    for (const m of moves) { 
        dirs[m]();
        if (--remainingSteps < (Math.abs(v) + Math.abs(h))) {  return false }
    }
    return !(h || v);
}

UPDATE I got that wrong, it does not work for all cases

Finally you could also use String.replace to solve

function returnsHome(m) {
    const rep = dir => (m = m.replace(dir, "")).length;
    return !(
        m.length % 2 || (m.length - rep(/D/g)) - (m.length - rep(/U/g)) || 
        m.length % 2 || rep(/L/g) - m.length
    );
}
\$\endgroup\$
2
\$\begingroup\$

It could be made more functional by avoiding the mutation of acc. The effects are contained within judgeCircle so it's not a big deal, but it feels like if you're going to mutate the accumulator, you might as well just use an imperative loop.

I also preferred to be explicit about the final check. I find the intent of !h && !v isn't quite as clear as h == 0 && v == 0;.

I ended up with:

const judgeCircle3 = moves => {
  const [hori, vert] = [...moves].reduce(([h, v], move) => {
    switch(move) {
      case "U":
        return [h, v + 1];

      case "D":
        return [h, v - 1];

      case "R":
        return [h + 1, v];

      case "L":
        return [h - 1, v];
    }

  }, [0, 0]);

  return hori == 0 && vert == 0;
};

The need for the switch here is unfortunate, but the only other alternative I could think of was some mess where a you'd do a lookup on a map which returned a function that returned a "altered" accumulator state.

I also got rid of the default since it didn't seem to be doing anything. You could have done error handling in there (and should in most cases), but if it's a challenge with predefined input, that's probably not necessary unless it's part of the challenge.

\$\endgroup\$
1
  • \$\begingroup\$ Good point with avoiding the acc. I'll keep this in mind for future tasks. \$\endgroup\$ Commented May 18, 2019 at 16:10

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.