Back to Freecodecamp

Challenge 160: Knight Moves

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6939b873185d8e00d453563f.md

latest2.1 KB
Original Source

--description--

Given the position of a knight on a chessboard, return the number of valid squares the knight can move to.

A standard chessboard is 8x8, with columns labeled A through H (left to right) and rows labeled 1 through 8 (bottom to top). It looks like this:

A8B8C8D8E8F8G8H8
A7B7C7D7E7F7G7H7
A6B6C6D6E6F6G6H6
A5B5C5D5E5F5G5H5
A4B4C4D4E4F4G4H4
A3B3C3D3E3F3G3H3
A2B2C2D2E2F2G2H2
A1B1C1D1E1F1G1H1

A knight moves in an "L" shape: two squares in one direction (horizontal or vertical), and one square in the perpendicular direction.

This means a knight can move to up to eight possible positions, but fewer when near the edges of the board. For example, if a knight was at A1, it could only move to B3 or C2.

--hints--

knightMoves("A1") should return 2.

js
assert.equal(knightMoves("A1"), 2);

knightMoves("D4") should return 8.

js
assert.equal(knightMoves("D4"), 8);

knightMoves("G6") should return 6.

js
assert.equal(knightMoves("G6"), 6);

knightMoves("B8") should return 3.

js
assert.equal(knightMoves("B8"), 3);

knightMoves("H3") should return 4.

js
assert.equal(knightMoves("H3"), 4);

--seed--

--seed-contents--

js
function knightMoves(position) {

  return position;
}

--solutions--

js
function knightMoves(position) {
  const col = position[0].charCodeAt(0) - 65;
  const row = parseInt(position[1]) - 1;

  const moves = [
    [2, 1], [2, -1],
    [-2, 1], [-2, -1],
    [1, 2], [1, -2],
    [-1, 2], [-1, -2]
  ];

  let valid = 0;

  for (const [dx, dy] of moves) {
    const newCol = col + dx;
    const newRow = row + dy;

    if (newCol >= 0 && newCol < 8 && newRow >= 0 && newRow < 8) {
      valid++;
    }
  }

  return valid;
}