Skip to content

Commit

Permalink
Merge pull request #11 from andrerademacher/10-shortest-knight-path
Browse files Browse the repository at this point in the history
done!
  • Loading branch information
andrerademacher authored Jan 19, 2024
2 parents 3baada2 + d89bc43 commit e6bb1b0
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 0 deletions.
28 changes: 28 additions & 0 deletions kata/ShortestKnightPath/Knight.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
SIZE = 8
EMPTY = -1
POSSIBLE_MOVES = [(1, 2), (2, 1), (-1, 2), (-2, 1), (1, -2), (2, -1), (-1, -2), (-2, -1)]

def knight(p1, p2) -> int:

start = toCoordinates(p1)
end = toCoordinates(p2)
board = [ [EMPTY]*SIZE for line in range(SIZE)]
board[start[0]][start[1]] = 0

moves = 0
while board[end[0]][end[1]] == EMPTY:
for x in range(SIZE):
for y in range(SIZE):
if board[x][y] == moves:
for delta in POSSIBLE_MOVES:
newX = x + delta[0]
newY = y + delta[1]
if 0 <= newX and newX < SIZE and 0 <= newY and newY < SIZE:
board[newX][newY] = moves + 1

moves+=1
return moves

# transforms the algebraic string notation (e.g. 'e4') into numeric, zero based coordinates [4, 3]
def toCoordinates(algebraicNotation: str) -> list:
return [ord(algebraicNotation[0:1]) - ord('a'), int(algebraicNotation[1:2]) - 1]
13 changes: 13 additions & 0 deletions kata/ShortestKnightPath/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Shortest Knight Path

Given two different positions on a chess board, find the least number of moves it would take a knight to get from one to the other. The positions will be passed as two arguments in algebraic notation. For example, `knight("a3", "b5")` should return 1.

The knight is not allowed to move off the board. The board is 8x8.

For information on knight moves, see https://en.wikipedia.org/wiki/Knight_%28chess%29

For information on algebraic notation, see https://en.wikipedia.org/wiki/Algebraic_notation_%28chess%29

(Warning: many of the tests were generated randomly. If any do not work, the test cases will return the input, output, and expected output; please post them.)

[See this kata in Codewars](https://www.codewars.com/kata/549ee8b47111a81214000941)
Empty file.
14 changes: 14 additions & 0 deletions kata/ShortestKnightPath/test_Knight.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import codewars_test as test
from Knight import knight


@test.describe("Shortest knight path")
def shortest_night_path_test():
@test.it("starting at a1")
def a1_tests():
# test.assert_equals(knight('a1', 'c1'), 2)
# test.assert_equals(knight('a1', 'f1'), 3)
# test.assert_equals(knight('a1', 'f3'), 3)
# test.assert_equals(knight('a1', 'f4'), 4)
# test.assert_equals(knight('a1', 'f7'), 5)
test.assert_equals(knight('d1', 'a2'), 2)

0 comments on commit e6bb1b0

Please sign in to comment.