Chess Knight

Description


Given a position of a knight on the standard chessboard, find the number of different moves the knight can perform.

The knight can move to a square that is two squares horizontally and one square vertically, or two squares vertically and one square horizontally away from it. The complete move therefore looks like the letter L. Check out the image below to see all valid moves for a knight piece that is placed on one of the central squares.

Example

  • For cell = "a1", the output should be chessKnight(cell) = 2.

  • For cell = "c2", the output should be chessKnight(cell) = 6.

Input/Output

  • [execution time limit] 4 seconds (js)

  • [input] string cell

String consisting of 2 letters - coordinates of the knight on an 8 × 8 chessboard in chess notation.

Note: Each square of the chessboard is identified by a unique coordinate pair—a letter and a number. The vertical columns of squares from white’s left to the right are labeled 'a' through 'h'. The horizontal rows of squares are numbered 1 to 8 starting from white’s side of the board. Thus each square has a unique identification as a string consisting of two characters: the first is the column label, and the second in the row number.

  • [output] integer

[JavaScript (ES6)] Syntax Tips

1
2
3
4
5
6
// Prints help message to the console
// Returns a string
function helloWorld(name) {
    console.log("This prints to the console when you Run Tests");
    return "Hello, " + name;
}

Solution


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
function chessKnight(cell) {
    cell = cell.split('');
    cell[0] = cell[0].charCodeAt(0) - 'a'.charCodeAt(0) +1;
    cell[1] = Number(cell[1]);
    aux = [[1,1], [1,1],[1,1],[1,1]]
    var ret = 8;
    if(cell[0] < 3){
        ret -= aux[0][0];
        ret -= aux[0][1];
        aux[0][0] = 0;
        aux[0][1] = 0;
    }
    if(cell[0] < 2) {
        ret -= aux[1][0];
        ret -= aux[1][1];
        aux[1][0] = 0;
        aux[1][1] = 0;
    }
    if(cell[0] > 6){
        ret -= aux[3][0];
        ret -= aux[3][1];
        aux[3][0] = 0;
        aux[3][1] = 0;
    }
    if(cell[0] > 7){
        ret -= aux[2][0];
        ret -= aux[2][1];
        aux[2][0] = 0;
        aux[2][1] = 0;
    }
    if(cell[1] < 3){
        ret -= aux[1][1];
        ret -= aux[2][1];
        aux[1][1] = 0;
        aux[2][1] = 0;
    }
    if(cell[1] < 2){
        ret -= aux[0][1];
        ret -= aux[3][1];
        aux[0][1] = 0;
        aux[3][1] = 0;
    }
    if(cell[1] > 6){
        ret -= aux[1][0];
        ret -= aux[2][0];
        aux[1][0] = 0;
        aux[2][0] = 0;
    }
    if(cell[1] > 7){
        ret -= aux[0][0];
        ret -= aux[3][0];
        aux[0][0] = 0;
        aux[3][0] = 0;
    }
    
    return ret;
}