I’ve been doing the occasional challenge from https://www.dailycodingchallenge.dev/subscribe
Yesterday’s was to write a program to generate Knight’s tours - https://en.wikipedia.org/wiki/Knight's_tour for more information.
I got as far as:
# Knight's tour problem
def find_knights_tour(start_x, start_y, board_size):
and Copilot finished the job for me:
# Knight's tour problem
def find_knights_tour(start_x, start_y, board_size):
# Initialize the board
board = [[0 for i in range(board_size)] for j in range(board_size)]
board[start_x][start_y] = 1
# Define the moves a knight can make
moves = [(2, 1), (1, 2), (-1, 2), (-2, 1),
(-2, -1), (-1, -2), (1, -2), (2, -1)]
# Recursive function to find the knight's tour
def find_tour(x, y, move_number):
if move_number == board_size * board_size:
return True
for move in moves:
new_x = x + move[0]
new_y = y + move[1]
if 0 <= new_x < board_size and 0 <= new_y < board_size and board[new_x][new_y] == 0:
board[new_x][new_y] = move_number + 1
if find_tour(new_x, new_y, move_number + 1):
return True
board[new_x][new_y] = 0
return False
# Start the recursive function
if find_tour(start_x, start_y, 1):
return board
else:
return None
Irritatingly, it appears to work just fine.