85 lines
1.8 KiB
Python
85 lines
1.8 KiB
Python
import sys
|
|
from copy import deepcopy
|
|
|
|
from random import randint, shuffle
|
|
|
|
import numpy as np
|
|
|
|
def calcFitness(board):
|
|
return -np.sum([len(set(board[:, i])) != 9 for i in range(9)])
|
|
|
|
def initSodoku():
|
|
row = np.arange(1,10)
|
|
|
|
board = np.tile(row, (9, 1))
|
|
printBoard(board)
|
|
return board
|
|
|
|
def shuffleBoard(board):
|
|
for i in range(9):
|
|
shuffle(board[i])
|
|
|
|
def step(board):
|
|
newBoard = deepcopy(board)
|
|
x = randint(0, 8)
|
|
|
|
y1 = randint(0,8)
|
|
y2 = randint(0,8)
|
|
while y2 == y1:
|
|
y2 = randint(0, 8)
|
|
|
|
newBoard[x][y1], newBoard[x][y2] = board[x][y2], board[x][y1]
|
|
return newBoard
|
|
|
|
def printRed(text):
|
|
return format(f"\033[1;31m{text}\033[0;0m")
|
|
|
|
def printBoard(board):
|
|
print("\n")
|
|
for i in range(len(board)):
|
|
if (i % 3 == 0 and i != 0):
|
|
print("------+------+------")
|
|
for j in range(len(board[i])):
|
|
if (j % 3 == 0 and j != 0):
|
|
sys.stdout.write("|")
|
|
if(isWrong(board,i,j)):
|
|
sys.stdout.write(printRed(board[i][j]) + " ")
|
|
else:
|
|
sys.stdout.write(str(board[i][j]) + " ")
|
|
|
|
print("")
|
|
|
|
def isWrong(board, i, j):
|
|
x = board[i][j]
|
|
for y in range(9):
|
|
if y == i:
|
|
continue
|
|
if x == board[y][j]:
|
|
return True
|
|
return False
|
|
|
|
|
|
def __main__():
|
|
iterations = 0
|
|
|
|
board = initSodoku()
|
|
fitness = calcFitness(board)
|
|
while fitness < 0:
|
|
newBoard = step(board)
|
|
|
|
newFitness = calcFitness(newBoard)
|
|
if(newFitness >= fitness):
|
|
board = deepcopy(newBoard)
|
|
if(newFitness > fitness):
|
|
printBoard(board)
|
|
fitness = newFitness
|
|
print(f"Fitness: {fitness}")
|
|
|
|
iterations += 1
|
|
|
|
print(f"Total iterations: {iterations}")
|
|
printBoard(board)
|
|
|
|
|
|
|
|
__main__() |