Created
May 18, 2018 22:29
-
-
Save newton-migosi/769c31bf989639edde91658ec74e4798 to your computer and use it in GitHub Desktop.
trying out sudoku
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import random | |
def main(): | |
generate_sudoku() | |
initial_state = load_sudoku() | |
sudoku = Sudoku(initial_state) | |
print(sudoku) | |
def generate_sudoku(): | |
with open('sudoku.txt','w') as sudoku_file: | |
blueprint = ('{},'*8 + '{} \n')*9 | |
state = fill_slots() | |
sudoku_file.write(blueprint.format(*state)) | |
def relatives(slot): | |
row = slot // 9 | |
row_relatives = [row*9+i for i in range(9)] | |
#print(row) | |
column = slot % 9 | |
column_relatives = [i+column for i in range(0,81,9)] | |
#print(column) | |
box = (row - row % 3)*9 + (column - column % 3) | |
#box_relatives = [box, box+1, box+2, box+9, box+10, box+11, box+18, box+19, box+20] | |
box_relatives = [box + row + column * 9 for row in range(3) for column in range(3)] | |
#print(box) | |
return set(row_relatives + box_relatives + column_relatives) | |
def fill_slots(): | |
state = [0] * 81 | |
slots = set([random.randint(0,80) for _ in range(36)]) | |
for slot in slots: | |
state[slot] = random.randint(1,9) | |
for relative in relatives(slot) & slots: | |
while slot != relative and state[slot] == state[relative]: | |
state[slot] = random.randint(1,9) | |
#for relative in relatives(4): | |
#state[relative] = random.randint(1,9) | |
return state | |
def load_sudoku(): | |
if len(sys.argv) > 1: | |
raw = read_file(sys.argv[1]) | |
else: | |
raw = request_file() | |
return raw | |
def read_file(fname): | |
try: | |
arr = [] | |
with open(fname, 'r') as sudoku_file: | |
arr = [int(row) for line in sudoku_file for row in line.strip().split(',')] | |
except Exception as e: | |
print("Couldn't read file {}. msg: {}".format(fname,e)) | |
arr = request_file() | |
return arr | |
def request_file(): | |
fname = input("Enter location of file containing the Sudoku puzzle:") | |
return read_file(fname) | |
class Sudoku: | |
def __init__(self, initial_state): | |
self.view = initial_state | |
def __str__(self): | |
template = ("{} | {} | {} || {} | {} | {} || {} | {} | {}\n" + '-' * 35 + '\n') * 9 | |
return template.format(*self.view) | |
if __name__ == '__main__': | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment