diff --git a/kata/ShortestKnightPath/Knight.py b/kata/ShortestKnightPath/Knight.py new file mode 100644 index 0000000..093c508 --- /dev/null +++ b/kata/ShortestKnightPath/Knight.py @@ -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] \ No newline at end of file diff --git a/kata/ShortestKnightPath/README.md b/kata/ShortestKnightPath/README.md new file mode 100644 index 0000000..382ef15 --- /dev/null +++ b/kata/ShortestKnightPath/README.md @@ -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) \ No newline at end of file diff --git a/kata/ShortestKnightPath/__init__.py b/kata/ShortestKnightPath/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/kata/ShortestKnightPath/test_Knight.py b/kata/ShortestKnightPath/test_Knight.py new file mode 100644 index 0000000..108ee52 --- /dev/null +++ b/kata/ShortestKnightPath/test_Knight.py @@ -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) \ No newline at end of file