Created
August 12, 2011 06:59
-
-
Save y-ogi/1141606 to your computer and use it in GitHub Desktop.
generate 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
#!/usr/bin/env python | |
import random | |
import copy | |
NUMS = [1, 2, 3, 4, 5, 6, 7, 8 , 9] | |
class Sudoku(object): | |
def __init__(self): | |
self.box = [] | |
def generate(self): | |
while True: | |
if self._generate(): | |
break | |
self.box = [] | |
def _generate(self): | |
for i in range(0, 9): | |
row = [] | |
for j in range(0, 9): | |
nums = copy.copy(NUMS) | |
box = self.box_at_point(j, i) | |
col = self.col_at_index(j) | |
for v in (row + box + col): | |
if v in nums: | |
nums.remove(v) | |
if len(nums) == 0: | |
self.box.append(row) | |
return False | |
row.append(random.choice(nums)) | |
self.box.append(row) | |
return True | |
def evaluate(self): | |
pass | |
def col_at_index(self, index): | |
cols = [] | |
for row in self.box: | |
cols.append(row[index]) | |
return cols | |
def box_at_point(self, x, y): | |
x_min = int(x / 3) * 3 | |
x_max = x_min + 3 | |
y_min = int(y / 3) * 3 | |
y_max = y_min + 3 | |
box = [] | |
for i, row in enumerate(self.box): | |
if i >= y_min and i < y_max: | |
box = box + row[x_min:x_max] | |
return box | |
def p(self): | |
for row in self.box: | |
print row | |
def generate_sudoku(): | |
sudoku = Sudoku() | |
sudoku.generate() | |
sudoku.p() | |
if __name__ == '__main__': | |
generate_sudoku() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment