Jarosh / Exercises

18 stars 3 forks source link

Knight problem #2

Open u3k opened 7 years ago

u3k commented 7 years ago

really appreciate your effort and detailed explanation for the problem (which I didn't manage to solve on time). here's a "corrected" with a slightly more transparent conditions:

function solution(A, B)
{
    let dx = Math.abs(A);
    let dy = Math.abs(B);

    const limit = 100000000;

    let moves = Math.max(Math.floor((dx+1)/2), Math.floor((dy+1)/2), Math.floor((dx+dy+2)/3));

    while ((moves%2)!=(dx+dy)%2 && moves <= limit) moves++;

    return moves <= limit ? moves : -2;
}
u3k commented 7 years ago

@RatebJabbar it builds on @Jarosh's approach, but just does it a bit more defensive. Last while is where we close on exact number of moves. See https://github.com/Jarosh/Exercises/wiki/Finding-the-shortest-path-as-for-knight--in-the-game-of-chess-on-an-infinite-board for the explanations.

cytrowski commented 7 years ago

I'm looking at the task description now and I can't figure out where do we have a phrase telling us that the knight can't go backwards. If it's not stated there then every field can be reached. Can you explain me why you made an assumption about the knight moving forward only?

u3k commented 7 years ago

@cytrowski javascriptMath.abs() takes into account that knight can move to negative coordinate(s) - "backwards"

cytrowski commented 7 years ago

I didn't mean that. I don't get why after moving by vector [2, 1] I cannot move by [-2, 1] in the next turn. That way I can reach any field - no need do draw a set of unreachable fields then.

u3k commented 7 years ago

@cytrowski ah! this question should be addressed to @Jarosh, not me :) this solution does not have unreachable fields assumption :)

cytrowski commented 7 years ago

True - I should make a separate issue for that ;)

seyfer commented 7 years ago

@u3k , @cytrowski Also, we should consider special cases [1,0] and [2,2]. I think it's better to hard code them

// 2 corner cases
    if ($A == 1 && $B == 0) {
        return 3;
    }
    if ($A == 2 && $B == 2) {
        return 4;
    }

@Jarosh, and what about 0 in your solution? For example, [1,0] leads to DIVISION BY ZERO error. Or you consider any back move as not reachable?

seyfer commented 7 years ago

@u3k why your solution returns 1 for [1,0] and 2 for [2,2] ? Just try to reach these points on a chess board and you will see that you need 3 and 4. Or you also consider any back move as not reachable?

There wasn't a restriction on back moves in the task.