MLE/01_sudoku_hillclimber.py

42 lines
1.4 KiB
Python

"""
Implementiere einen Hill-Climbing-Algorithmus, der die Zahlen in
einem SUDOKU-Feld durch vertauschen innerhalb einer Zeile so
umsortiert, dass sie die SUDOKU-Bedingung auch für die Spalten
erfüllen.
"""
import numpy as np
import random
board = np.array([
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9]
])
board_size = len(board) # Board is always quadratic
last_fitness = -np.sum([len(set(board[:, i])) != 9 for i in range(9)]) # -9
print("Working...")
while -np.sum([len(set(board[:, i])) != 9 for i in range(9)]):
# swap col in row with random other col
rand_row = random.randrange(board_size)
rand_col = random.randrange(board_size)
swap_col = (rand_col + random.randrange(1, board_size)) % board_size
board[rand_row, rand_col], board[rand_row, swap_col] = board[rand_row, swap_col], board[rand_row, rand_col]
current_fitness = -np.sum([len(set(board[:, i])) != 9 for i in range(9)])
if current_fitness >= last_fitness:
last_fitness = current_fitness
else:
board[rand_row, swap_col], board[rand_row, rand_col] = board[rand_row, rand_col], board[rand_row, swap_col]
print(last_fitness) # debugging
print(board)