Created
July 25, 2024 13:59
-
-
Save arifsuhan/67bddef3104da13bb74b769905e78291 to your computer and use it in GitHub Desktop.
SUDOKU
This file contains hidden or 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
from random import shuffle | |
class SUDOKU: | |
def __init__(self,size=3,level=1): | |
self.cube_size = size | |
self.level = level | |
self.n_min = 1 | |
self.n_max = size * size | |
self.matrix = [] | |
def flat_to_matrix(self,flat): | |
result = [ [] for _ in range(self.cube_size * self.cube_size) ] | |
index = 0 | |
count = 0 | |
cycle = 0 | |
for row in flat: | |
for i in range(self.cube_size): | |
if index == self.cube_size: | |
cycle += 1 | |
index = 0 | |
if cycle%self.cube_size==0: | |
count += self.cube_size | |
cycle = 0 | |
temp = row[self.cube_size*i : self.cube_size*(i+1)] | |
result[count + index].append(temp) | |
index += 1 | |
return result | |
def matrix_to_flat(self,matrix): | |
result = [ [] for _ in range(self.cube_size * self.cube_size) ] | |
index = 0 | |
count = 0 | |
cycle = 0 | |
for row in matrix: | |
for i in range(self.cube_size): | |
if index == self.cube_size: | |
cycle += 1 | |
index = 0 | |
if cycle%self.cube_size==0: | |
count += self.cube_size | |
cycle = 0 | |
temp = row[index] | |
result[count + index] += temp | |
index += 1 | |
return result | |
def transpose(self,matrix): | |
length = self.cube_size * self.cube_size | |
transpose = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))] | |
return transpose | |
def standard(self): | |
result = [] | |
temp_matrix = [] | |
temp_data = [x for x in range(self.n_min, self.n_max + 1)] | |
for _ in range(self.cube_size): | |
temp = temp_data | |
for _ in range(self.cube_size): | |
temp_matrix.append(temp) | |
temp = self.shift_left(temp, shift_index=self.cube_size) | |
temp_data = self.shift_left(temp_data, shift_index=1) | |
return temp_matrix | |
def shift_left(self, data, shift_index = 3): | |
result = data[shift_index:] + data[:shift_index] | |
return result | |
def generate(self): | |
self.matrix = self.standard() | |
self.matrix = self.flat_to_matrix(self.matrix) | |
self.validate() | |
def validate(self): | |
# inside cube | |
for cube in self.matrix: | |
temp = [ y for x in cube for y in x] | |
print(temp,sum(temp)) | |
# row sum | |
self.matrix = self.matrix_to_flat(self.matrix) | |
for cube in self.matrix: | |
print(sum(cube)) | |
# col sum | |
self.matrix = self.transpose(self.matrix) | |
for cube in self.matrix: | |
print(sum(cube)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment