Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import itertools
- import numpy as np
- import random
- import time
- def check_doubles_in_list(liste):
- print(f"Length of list: {len(liste)}")
- counter = 0
- for i, entry in enumerate(liste):
- for j, next_entry in enumerate(liste[i+1:len(liste)]):
- j += i+1
- if entry == next_entry:
- print(f"Double found: {entry} (index={i}) == {next_entry} (index={j}))")
- counter += 1
- print(f"{counter} double entries found.")
- def conv_console2code(console_output):
- char_list = ["np.array("]
- for counter, char in enumerate(console_output):
- if char != ".":
- char_list.append(char)
- if char == "." and console_output[counter+1] != "]":
- char_list.append(",")
- try:
- if char == "]" and console_output[counter+1] != "]":
- char_list.append(",")
- except:
- pass
- char_list.append(")")
- code = "".join(char_list)
- print(code)
- def print_board(board):
- board = np.asarray(board, dtype="int")
- end_case1 = " "
- end_case2 = " || "
- first_row = True
- for row_counter, row in enumerate(board):
- if not first_row:
- if (row_counter)%3 == 0:
- print(15*"= = ")
- else:
- print("\n")
- else:
- first_row = False
- for col_counter, col in enumerate(row):
- if (col_counter+1)%3 == 0:
- print(col, end=end_case2)
- else:
- print(col, end=end_case1)
- if col_counter == 8: # end of line
- print("\n")
- def count_nonzero(board):
- counter = 0
- for row in board:
- for num in row:
- if num != 0:
- counter += 1
- return counter
- def possible(board,num,row,col,printReason=False):
- # check row
- for i in range(9):
- if board[row, i] == num:
- if printReason:
- print(f"{num} tested at {row},{col} --> already in the same row (at col {i})")
- return False
- # check column
- for i in range(9):
- if board[i, col] == num:
- if printReason:
- print(f"{num} tested at {row},{col} --> already in the same col (at row {i})")
- return False
- # check square
- row0 = (row//3)*3
- col0 = (col//3)*3
- for y in range(row0, row0+3):
- for x in range(col0, col0+3):
- if board[y,x] == num:
- if printReason:
- print(f"{num} tested at {row},{col} --> already in the same square (at square with upper left corner {row0}, {col0})")
- return False
- return True
- def solveSudoku():
- global board
- global counter
- global unique_STOP
- global STOP
- for row in range(9):
- for col in range(9):
- if board[row,col] == 0:
- nums1to9 = np.arange(1,10)
- random.shuffle(nums1to9)
- for num in nums1to9:
- if possible(board, num, row, col):
- board[row,col] = num
- solveSudoku()
- if not unique_STOP:
- if not STOP:
- board[row,col] = 0 # try new possibilities (non-unique Sudoku)
- return # backtracking (empty field, but no number fits) --> does not print out the "wrong" Sudoku
- counter += 1
- '''if not suppress_print:
- # Check if Sudoku is the same
- if counter == 1:
- if np.array_equal(first_sudoku, board):
- print("Sudoku is not solvable/over-constrained!")
- return
- if not suppress_print:
- print(f"Solution #{counter}:\n")
- print(board, "\n")
- ## PREVENT CPU OVERLOAD ##
- if counter > 100:
- return'''
- STOP = True
- return board
- def createSudoku():
- global board
- global counter
- global unique_STOP
- global STOP
- whileTrue_counter1 = 0
- while True:
- board = np.zeros((9,9))
- position = 1
- BREAK_for_loop = False
- x = 70
- for i in range(x):
- #convert position to coordinate
- col = (position-1)%9
- row = (position-1)//9
- whileTrue_counter2 = 0
- while True:
- num = random.randint(1,9)
- if possible(board, num, row, col):
- board[row,col] = num
- #print(f"{num} inserted at position ({row}, {col}). Still {x-1-i} entries left to fill.")
- break
- whileTrue_counter2 += 1
- if whileTrue_counter2 > 100:
- BREAK_for_loop = True
- break
- if BREAK_for_loop:
- #print(f"Rare case occurred! {x} numbers couldn't be placed randomly according to Sudoku rules. New attempt...")
- break
- position += 1
- unique_STOP = False
- STOP = False
- if not BREAK_for_loop:
- counter = 0
- #print(first_sudoku)
- solveSudoku()
- if counter == 1:
- #print("Found unique Sudoku!!!")
- break
- if counter > 1:
- print(f"counter for unique sudoku > 1, it is: {counter}", end=", ")
- whileTrue_counter1 += 1
- if whileTrue_counter1 in [10, 100, 1000, 10000, 100000, 200000, 300000]:
- print(f"{whileTrue_counter1}th attempt to find unique Sudoku...")
- # print("---")
- # print(sudoku)
- # print("----")
- ## user selects difficulty level
- while True:
- numClues_input = input("Choose difficulty level:\n1) Extremely easy\n2) Easy\n3) Medium\n4) Difficult\n5) Evil\n\n--> ")
- if numClues_input.lower() in ["1", "1)", "one", "eins", "i", "extremely easy"]:
- numClues = random.randint(47,80)
- break
- elif numClues_input.lower() in ["2", "2)", "two", "zwei", "ii", "easy"]:
- numClues = random.randint(36,46)
- break
- elif numClues_input.lower() in ["3", "3)", "three", "drei", "iii", "medium"]:
- numClues = random.randint(32,35)
- break
- elif numClues_input.lower() in ["4", "4)", "four", "vier", "iv", "difficult"]:
- numClues = random.randint(28,31)
- break
- elif numClues_input.lower() in ["5", "5)", "five", "fünf", "v", "evil"]:
- numClues = random.randint(17,27)
- break
- print("\nSelect difficulty level...\n")
- print(f"\nYou have selected difficulty level {numClues_input}. Therefore you will get {numClues} clues.\n")
- numRemoveClues = 81-numClues
- ## remove up to 81-17=64 clues until there is a unique solution
- allCoordinates = list(itertools.product(range(0,9), repeat=2))
- while_counter = 0
- start = time.time()
- SAVE_board = board.copy()
- while True:
- board = SAVE_board.copy()
- removeCoordinates = random.sample(allCoordinates, numRemoveClues)
- for coord in removeCoordinates:
- row = coord[0]
- col = coord[1]
- board[row, col] = 0
- counter = 0
- board_removedStuff = board.copy()
- solveSudoku()
- if counter == 1:
- print_board(board_removedStuff)
- return board_removedStuff
- if counter > 1:
- print(f"L{counter}", end=", ")
- while_counter += 1
- if while_counter in [10,100,1000,10000,100000,1000000]:
- print(f"{while_counter} Sudokus with {numClues} clues have been found so far, but none of them is unique...")
- stop = time.time()
- elapsed_time = stop-start
- if elapsed_time > 120:
- print("Time elapsed has exceed the maximum waiting time of 120s.")
- break
- board = createSudoku()
- counter=0
- solveSudoku()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement