Exemplo n.º 1
0
 def traiteSaisieGrille(self, csock, donnejesRecues):
     self.ejnoncej = ''
     # 11=3&12=1&13=&...&98=&99=&raz=raz
     if 'raz=raz' in donnejesRecues:
         self.afficheSaisieGrille(csock)
         return
     # 11=3&12=1&13=&...&98=&99=&soumettre=soumettre
     match = re.search('(11=.*)&soumettre=soumettre', donnejesRecues)
     if not match:
         print('saisie-grille INCONNU')
         self.afficheSaisieGrille(csock)
         return
     for affectation in match.group(1).split('&'):
         # 12=1 ou 13=
         valeur = affectation.split('=')[1]
         if valeur == '': self.ejnoncej += '.'
         else: self.ejnoncej += valeur
         # max 81 + 8 virgules
         if len(self.ejnoncej) == 89: break
         # insertion barre sejparation
         if len(self.ejnoncej) % 10 == 9: self.ejnoncej += '|'
     if len(self.ejnoncej) != 89:
         print('saisie-grille ERRONNÉE ({})'.format(len(self.ejnoncej)))
         self.afficheSaisieGrille(csock)
         return
     # avec le programme de calcul maintenant
     lignes = self.ejnoncej.replace('|', ',')
     lignes = lignes.replace('.', '0')
     self.sudoku = Sudoku(lignes)
     # affiche
     self.afficheEnTeste(csock)
     self.afficheTitreEtSaisie(csock)
     self.afficheCalculPartiel(csock)
     self.afficheValeursPossibles(csock)
     self.afficheQueue(csock)
Exemplo n.º 2
0
    def test_hardest(self):
        grid = [
            [8,0,0,0,0,0,0,0,0],
            [0,0,3,6,0,0,0,0,0],
            [0,7,0,0,9,0,2,0,0],
            [0,5,0,0,0,7,0,0,0],
            [0,0,0,0,4,5,7,0,0],
            [0,0,0,1,0,0,0,3,0],
            [0,0,1,0,0,0,0,6,8],
            [0,0,8,5,0,0,0,1,0],
            [0,9,0,0,0,0,4,0,0]
        ]

        expected = [
            [8,1,2,7,5,3,6,4,9],
            [9,4,3,6,8,2,1,7,5],
            [6,7,5,4,9,1,2,8,3],
            [1,5,4,2,3,7,8,9,6],
            [3,6,9,8,4,5,7,2,1],
            [2,8,7,1,6,9,5,3,4],
            [5,2,1,9,7,4,3,6,8],
            [4,3,8,5,2,6,9,1,7],
            [7,9,6,3,1,8,4,5,2]
        ]

        sudoku = Sudoku()

        actual = sudoku.solve((3, 3), grid)

        self.assertEquals(actual, expected)
Exemplo n.º 3
0
class SudokuTestCase4(unittest.TestCase):

    def setUp(self):
        self.sudoku = Sudoku([
            [2, 0, 6, 4, 0, 0, 0, 5, 3],
            [0, 0, 0, 2, 7, 5, 0, 9, 6],
            [5, 1, 7, 0, 3, 0, 0, 0, 4],
            [0, 3, 9, 8, 0, 0, 5, 1, 0],
            [7, 5, 0, 1, 0, 6, 3, 0, 0],
            [1, 0, 0, 0, 5, 3, 0, 6, 2],
            [0, 7, 0, 0, 6, 2, 4, 8, 0],
            [0, 0, 1, 3, 4, 0, 2, 0, 5],
            [4, 2, 8, 0, 1, 0, 6, 0, 0]
        ])

    def test_valid_solution(self):
        self.sudoku.solve()
        solution = np.array([
            [2, 9, 6, 4, 8, 1, 7, 5, 3],
            [8, 4, 3, 2, 7, 5, 1, 9, 6],
            [5, 1, 7, 6, 3, 9, 8, 2, 4],
            [6, 3, 9, 8, 2, 4, 5, 1, 7],
            [7, 5, 2, 1, 9, 6, 3, 4, 8],
            [1, 8, 4, 7, 5, 3, 9, 6, 2],
            [3, 7, 5, 9, 6, 2, 4, 8, 1],
            [9, 6, 1, 3, 4, 8, 2, 7, 5],
            [4, 2, 8, 5, 1, 7, 6, 3, 9]
        ])
        equality = {i == j for i, j in zip(
            self.sudoku.puzzle.flatten(), solution.flatten())}
        self.assertTrue(True in equality and False not in equality)
Exemplo n.º 4
0
class Juego(object):

    def __init__(self, nombre, dif = int):
        """
            Constructor de la clase Juego. Aquí se almacena toda la información
            correspondiente a un juego de sudoku.
            @param nombre, nombre del jugador.
            @param dif, dificultad del juego.
            @author Iván Aveiga
        """
        self.nombre = nombre
        self.dif = dif
        self.time = 0
        self.hints = 5
        self.juego = Sudoku() #tablero a jugar
        self.tablero = Sudoku()   #tablero lleno
        self.create(dif)

    def create(self, dif = int):
        """
            Crea un nuevo tablero de 9x9 enteros
            @param dif, dificultad del juego.
        """
        g = Generator()
        g.poblar_board()
        self.tablero.parse(g.board)
        g.gen_puzzle(dif)
        self.juego.parse(g.puzzle)
Exemplo n.º 5
0
    def test_Sudoku_4_gano(self):
        sudoku = Sudoku([["4", "2", "3", "1"],
                         ["1", "3", "2", "4"],
                         ["3", "1", "4", "2"],
                         ["2", "4", "1", "3"]])

        self.assertTrue(sudoku.gano())
Exemplo n.º 6
0
    def __init__(self, file_name, cnf_filename=None):
        if cnf_filename is None:
            #-- Set up and load in puzzle
            self.sudoku = Sudoku()
            self.puzzle_name = str(file_name[:-4])
            self.solution_filename = self.puzzle_name + ".sol"
            self.cnf_filename = self.puzzle_name + ".cnf"

            self.sudoku.load(file_name)
            self.sudoku.generate_cnf(self.cnf_filename)

        else:
            self.puzzle_name = str(file_name[:-4])
            self.solution_filename = self.puzzle_name + ".sol"
            self.cnf_filename = cnf_filename

        #-- Load in clauses
        clauses = []
        with open(self.cnf_filename, 'r') as cnf:
            lines = cnf.readlines()
        for line in lines:
            clause = list(map(int, line.rstrip('\n').strip().split(' ')))
            clauses.append(clause)

        #-- Make sudoku variables
        variables = [
            int(''.join(str(x) for x in var))
            for var in itertools.product(range(1, 10), repeat=3)
        ]

        #-- Set up generic class
        super().__init__(variables, clauses, problem_name='Sudoku')
Exemplo n.º 7
0
 def impossible_test(self):
     # impossible
     puzzles = [
         # From https://norvig.com/sudoku.html  -> column 4, no 1 possible because of triple 5-6 doubles and triple 1s
         '.....5.8....6.1.43..........1.5........1.6...3.......553.....61........4.........',
         # obvious doubles
         '12.......34...............5...........5..........................................',
         '11.......34...............5......................................................',
     ]
     for puzzle in puzzles:
         puzzle = str2grid(puzzle)
         s = Sudoku(puzzle)
         s.flush_candidates()
         self.assertFalse(s.check_possible()[0])
     # possible
     puzzles = [
         '280070309600104007745080006064830100102009800000201930006050701508090020070402050',
         '000010030009005008804006025000000600008004000120087000300900200065008000900000000',
         '1.....................................5..........................................',
     ]
     for puzzle in [puzzles[1]]:
         puzzle = str2grid(puzzle)
         s = Sudoku(puzzle)
         s.flush_candidates()
         self.assertTrue(s.check_possible()[0])
Exemplo n.º 8
0
    def __init__(self,line,verbose=False):
        Sudoku.__init__(self,line,verbose)     #initialize a basic sudoku object
        self.sn=int(math.sqrt(self.n))
        self.conflict=[]               #conflict[row][col]-->cells in conflict with [row][col]
        for row in range(self.n):      #[row][cel] encoded as integer row*self.n+col
            ROW=[]
            for col in range(self.n):
                setrowcol=self.computeConflicts(row,col)
                ROW.append(setrowcol)
            self.conflict.append(ROW)

        self.forbidden=[]  #forbidden[row][col]-->digits forbidden for [row][col]
        for row in range(self.n):
            ROW=[]
            for col in range(self.n):
                ROW.append([])
            self.forbidden.append(ROW)
        #no digit is forbidden at the beginning

        #now we look at the instance and some digits are forbidden for some cells
        for row in range(self.n):
            for col in range(self.n):
                if self.instance[row][col]!=0:
                    for x in self.conflict[row][col]:
                        rx=x/self.n; cx=x%self.n
                        self.forbidden[rx][cx].append(self.instance[row][col])
Exemplo n.º 9
0
    def test(self):
        grid = [
            [5, 3, 0, 0, 7, 0, 0, 0, 0],
            [6, 0, 0, 1, 9, 5, 0, 0, 0],
            [0, 9, 8, 0, 0, 0, 0, 6, 0],
            [8, 0, 0, 0, 6, 0, 0, 0, 3],
            [4, 0, 0, 8, 0, 3, 0, 0, 1],
            [7, 0, 0, 0, 2, 0, 0, 0, 6],
            [0, 6, 0, 0, 0, 0, 2, 8, 0],
            [0, 0, 0, 4, 1, 9, 0, 0, 5],
            [0, 0, 0, 0, 8, 0, 0, 7, 9]
        ]

        expected = [
            [5, 3, 4, 6, 7, 8, 9, 1, 2],
            [6, 7, 2, 1, 9, 5, 3, 4, 8],
            [1, 9, 8, 3, 4, 2, 5, 6, 7],
            [8, 5, 9, 7, 6, 1, 4, 2, 3],
            [4, 2, 6, 8, 5, 3, 7, 9, 1],
            [7, 1, 3, 9, 2, 4, 8, 5, 6],
            [9, 6, 1, 5, 3, 7, 2, 8, 4],
            [2, 8, 7, 4, 1, 9, 6, 3, 5],
            [3, 4, 5, 2, 8, 6, 1, 7, 9]
        ]

        sudoku = Sudoku()

        actual = sudoku.solve((3, 3), grid)

        self.assertEquals(actual, expected)
Exemplo n.º 10
0
    def run(self, problem):
        print("초기 시작")
        print("스도쿠 문제번호 : ")
        print("스도쿠 난이도 : ")
        temp = np.array(list(map(int, list(problem)))).reshape(3, 3, 3, 3)
        self.helpArray = Sudoku(
            np.array([[SubBlock(subblock) for subblock in subblocks]
                      for subblocks in temp]))
        print("helpArray: ")
        self.helpArray.printSudoku()
        self.manager = Manager(self.helpArray)
        count = self.gaCount
        while not self.end:  # and self.gaCount < 3:
            print("세대 : ", self.gaCount)
            print("fitness : ", self.manager.fmin)
            print("best solution: ")
            self.manager.sudokuPool[0].printSudoku()

            if count > 2000:
                self.restart()
                count = 1
            self.end = self.manager.nextGeneration()
            self.gaCount = self.gaCount + 1
            count += 1

        self.print()
Exemplo n.º 11
0
    def __init__(self, line, verbose=False):
        Sudoku.__init__(self, line, verbose)  #initialize a basic sudoku object
        self.sn = int(math.sqrt(self.n))
        self.conflict = [
        ]  #conflict[row][col]-->cells in conflict with [row][col]
        for row in range(
                self.n):  #[row][cel] encoded as integer row*self.n+col
            ROW = []
            for col in range(self.n):
                setrowcol = self.computeConflicts(row, col)
                ROW.append(setrowcol)
            self.conflict.append(ROW)

        self.forbidden = [
        ]  #forbidden[row][col]-->digits forbidden for [row][col]
        for row in range(self.n):
            ROW = []
            for col in range(self.n):
                ROW.append([])
            self.forbidden.append(ROW)
        #no digit is forbidden at the beginning

        #now we look at the instance and some digits are forbidden for some cells
        for row in range(self.n):
            for col in range(self.n):
                if self.instance[row][col] != 0:
                    for x in self.conflict[row][col]:
                        rx = x / self.n
                        cx = x % self.n
                        self.forbidden[rx][cx].append(self.instance[row][col])
Exemplo n.º 12
0
def sudoku(fname):

    f_path = os.path.join(app.config['UPLOAD_FOLDER'], fname)

    # create sudokuimage object
    sdku_img = SudokuImage(f_path)     
    
    # this would be a good point to check if the
    # image was processed correctly.  The number of rows/cols
    # not equal to 10 is a good indication of failure.
    # 
    # the object is set so that self.rows/cols = False if the
    # length is not equal to 10.
    
    if sdku_img.rows and sdku_img.cols:
        
        sudoku_grid = np.zeros((9,9), dtype = int)
        # note: empty cells will be denoted by 0        
        

        print 'ENTER THE FOR LOOP'
        # use knn to predict the value of non-empty sdku_img cells
        for cell in sdku_img.predict_cells():
            sudoku_grid[cell[0], cell[1]] = cell[2]
        
            
        print 'MAKES IT OUT OF THE FOR LOOP'


        no_failure = True
        solved_grid = sudoku_grid.copy()

        if request.method == 'POST':

            sdku = Sudoku(solved_grid) # create sudoku object

            no_failure, solution = sdku.solve() # solve sudoku
        
            # if sudoku cant be solved, redirect with error message
            if not no_failure:
                flash("Oops, I am having trouble with your Sudoku!  Let's try this again.")
                return redirect(url_for('sudokusolver'))


            return render_template('sudoku_image.html',image =
                                   url_for('static', 
                                           filename = 'uploaded_sudokus/'+fname),
                                   initial_sudoku = sudoku_grid, 
                                   solved_sudoku = solved_grid)
        
        # initial rendering to user, before they hit submit
        return render_template('sudoku_image.html',image =
                               url_for('static', 
                                       filename = 'uploaded_sudokus/'+fname),
                               initial_sudoku = sudoku_grid, 
                               solved_sudoku = solved_grid)

    else:
        flash("Oops, I am having trouble with your Sudoku!  Take a clearer photo and try again.")
        return redirect(url_for('sudokusolver'))
    def solveProblem(self, problem: Sudoku):
        # Fill in all the possible tiles with educated predictions.
        while True:
            if self.applyNakedSingle(problem):
                continue
            if self.applyNakedTuple(problem):
                continue
            break

        # Check if we find the solution after applying Sudoku.
        if self.goalTest(problem):
            return problem

        # Save updated state of the problem before making guesses with candidates.
        beforeUpdateProblem = copy.deepcopy(problem)

        # Backtrack from populated sudoku problem
        tile = self.findMostConstrainedTile(problem)
        for index in range(len(tile.candidates)):
            if not problem.isConflicting(tile.candidates[index],
                                         rowIndex=tile.rowIndex,
                                         colIndex=tile.colIndex):
                problem.assignValue(value=tile.candidates[index],
                                    row=tile.rowIndex,
                                    col=tile.colIndex)
                updatedProblem = self.solveProblem(problem)
                if self.goalTest(updatedProblem):
                    return updatedProblem
                else:
                    problem = beforeUpdateProblem
                    tile = problem.state[tile.rowIndex][tile.colIndex]
        # No candidates, Hit dead end
        return None
Exemplo n.º 14
0
    def setUp(self):

        self.user4 = Interfaz()
        self.user9 = Interfaz()

        lista4 = [["4", "x", "3", "1"], ["x", "3", "x", "x"],
                  ["3", "1", "x", "2"], ["x", "4", "x", "x"]]

        self.user4.tam = 4
        self.user4.level = "1"
        self.user4.game = Sudoku(lista4)

        lista9 = [["5", "3", "x", "x", "7", "x", "x", "x", "x"],
                  ["6", "x", "x", "x", "9", "5", "x", "x", "x"],
                  ["x", "9", "8", "x", "x", "x", "x", "6", "x"],
                  ["8", "x", "x", "x", "6", "x", "x", "x", "3"],
                  ["4", "x", "x", "8", "x", "3", "x", "x", "1"],
                  ["7", "x", "x", "x", "2", "x", "x", "x", "6"],
                  ["x", "6", "x", "x", "x", "x", "2", "8", "x"],
                  ["x", "x", "x", "4", "1", "9", "x", "x", "5"],
                  ["x", "x", "x", "x", "8", "x", "x", "7", "9"]]

        self.user9.tam = 9
        self.user9.level = "1"
        self.user9.game = Sudoku(lista9)
Exemplo n.º 15
0
def index():
    # delete old input and output images
    if os.path.exists(INPUT_IMAGE_PATH):
        os.remove(INPUT_IMAGE_PATH)
    if os.path.exists(OUTPUT_IMAGE_PATH):
        os.remove(OUTPUT_IMAGE_PATH)

    if request.method == 'POST':
        image = request.files['image']
        if image and allowed_image(image.filename):
            image.save(INPUT_IMAGE_PATH)
            sudoku = Sudoku(img_path=INPUT_IMAGE_PATH)
            status = sudoku.get_status()
            if status == 'solved':
                sudoku.save_solved_image(OUTPUT_IMAGE_PATH)
                return render_template('index.html',
                                       input_img=True,
                                       output_img=True)
            else:
                return render_template('index.html',
                                       input_img=True,
                                       status=status)
        else:
            return render_template('index.html', error=True)
    return render_template('index.html')
Exemplo n.º 16
0
	def __init__(self,line):
		Sudoku.__init__(self,line)
		self.conflict=[]
		for x in range(self.n):
			self.conflict.append([])

		for x in range(self.n): # inizializzo matrice dei conflitti
			for y in range(self.n):
				self.conflict[x].append([])

				""" inizializza la sottogriglia dei confitti"""
		for row in range(self.n):
			for col in range(self.n):
				for x in range(self.sn):
					for y in self.instance[(row/self.sn)*self.sn+x][(col/self.sn)*self.sn:(col/self.sn)*self.sn+self.sn]:
						if (y!=0 and y!= self.instance[row][col]):
							self.conflict[row][col].append(y)

				""" inizializza la colonna dei confitti"""
				k = ((row/self.sn)*self.sn)+(row%self.sn)+1
				while((row/self.sn) == (k/self.sn)):
					k=k+1
				if(k<=self.n):
					while( k < self.n):
						if(self.instance[k][col]!=0):
							self.conflict[row][col].append(self.instance[k][col])
						k=k+1

				k = ((row/self.sn)*self.sn)+(row%self.sn)-1
				while ((row/self.sn)==(k/self.sn)):
					k=k-1
				if(k > 0):
					while (k>0):
						if(self.instance[k][col]!=0):
							self.conflict[row][col].append(self.instance[k][col])
						k=k-1
					if(self.instance[k][col]!=0):
						self.conflict[row][col].append(self.instance[k][col])

				"""inizializza la riga dei confitti"""
				k = ((col/self.sn)*self.sn)+(col%self.sn)+1
				while((col/self.sn) == (k/self.sn)):
					k=k+1
				if(k<=self.n):
					while( k < self.n):
						if(self.instance[row][k]!=0):
							self.conflict[row][col].append(self.instance[row][k])
						k=k+1

				k = ((col/self.sn)*self.sn)+(col%self.sn)-1
				while ((col/self.sn)==(k/self.sn)):
					k=k-1
				if(k > 0):
					while (k>0):
						if(self.instance[row][k]!=0):
							self.conflict[row][col].append(self.instance[row][k])
						k=k-1
					if(self.instance[row][k]!=0):
						self.conflict[row][col].append(self.instance[row][k])
Exemplo n.º 17
0
 def test_sudoku_4x4(self):
     esperado = np.array([[2, 1, 3, 4],
                          [4, 3, 1, 2],
                          [1, 4, 2, 3],
                          [3, 2, 4, 1]])
     sudoku = Sudoku(self.tablero_4x4)
     self.assertTrue(sudoku.solve_sudoku()) 
     self.assertEqual(esperado.any(),(sudoku.sudoku).any(),msg="Compara Resultado esperado con el resultado obtenido, True--> si son iguales, False-->si no lo son")
Exemplo n.º 18
0
 def setUp(self):
     self.table = ["53xx7xxxx", "6xx195xxx", "x98xxxx6x",
                   "8xxx6xxx3", "4xx8x3xx1", "7xxx2xxx6",
                   "x6xxxx28x", "xxx419xx5", "xxxx8xx79"]
     self.sudoku = Sudoku(self.table, 9)
     self.ori_pos = ["00", "01", "04", "10", "13", "14", "15", "21", "22",
                     "27", "30", "34", "38", "40", "43", "45", "48", "50",
                     "54", "58", "61", "66", "67", "73", "74", "75", "78",
                     "84", "87", "88"]
Exemplo n.º 19
0
def sudoku(fname):

    f_path = os.path.join(application.config['UPLOAD_FOLDER'], fname)
    

    # create sudokuimage object
    sdku_img = SudokuImage(f_path)     
    
    # catch any initial image processing errors
    # if len(rows/cols) != 10, the object sets them to false
    if sdku_img.rows and sdku_img.cols:
        
        sudoku_grid = np.zeros((9,9), dtype = int)
        # note: empty cells will be denoted by 0        
        

        # use knn to predict the value of non-empty sdku_img cells
        for cell in sdku_img.predict_cells():
            sudoku_grid[cell[0], cell[1]] = cell[2]
        

        no_failure = True
        solved_grid = sudoku_grid.copy()

        if request.method == 'POST':

            sdku = Sudoku(solved_grid) # create sudoku object

            no_failure, solution = sdku.solve() # solve sudoku
        

            # if sudoku cant be solved, redirect with error message
            # typically this is due to bad prediction
            if not no_failure:
                flash("Oops, I am having trouble processing your Sudoku!  Take a clearer photo and try again.")
                return redirect(url_for('sudokusolver'))

                
            # render when everything goes according to plan
            return render_template('sudoku_image.html',image =
                                   url_for('static', 
                                           filename = 'uploads/'+fname),
                                   initial_sudoku = sudoku_grid, 
                                   solved_sudoku = solved_grid)
        
        # initial rendering to user, before they hit submit
        return render_template('sudoku_image.html',image =
                               url_for('static', 
                                       filename = 'uploads/'+fname),
                               initial_sudoku = sudoku_grid, 
                               solved_sudoku = solved_grid)

    else:

        # this is rendered when the image can't be processed initially
        flash("Oops, I am having trouble processing your Sudoku!  Take a clearer photo and try again.")
        return redirect(url_for('sudokusolver'))
Exemplo n.º 20
0
def sudoku(fname):
    f_path = os.path.join(application.config['UPLOAD_FOLDER'], fname)
    

    # create sudokuimage object
    sdku_img = SudokuImage(f_path)     
    
    # catch any initial image processing errors
    # if len(rows/cols) != 10, the object sets them to false
    if sdku_img.rows and sdku_img.cols:
        
        sudoku_grid = np.zeros((9,9), dtype = int)
        # note: empty cells will be denoted by 0        
        

        # use knn to predict the value of non-empty sdku_img cells
        for cell in sdku_img.predict_cells():
            sudoku_grid[cell[0], cell[1]] = cell[2]
        

        no_failure = True
        solved_grid = sudoku_grid.copy()

        if request.method == 'POST':

            sdku = Sudoku(solved_grid) # create sudoku object

            no_failure, solution = sdku.solve() # solve sudoku
        

            # if sudoku cant be solved, redirect with error message
            # typically this is due to bad prediction
            if not no_failure:
                flash("Oops, I am having trouble processing your Sudoku!  Take a clearer photo and try again.")
                return redirect(url_for('sudokusolver'))

                
            # render when everything goes according to plan
            return render_template('sudoku_image.html',image =
                                   url_for('static', 
                                           filename = 'uploads/'+fname),
                                   initial_sudoku = sudoku_grid, 
                                   solved_sudoku = solved_grid)
        
        # initial rendering to user, before they hit submit
        return render_template('sudoku_image.html',image =
                               url_for('static', 
                                       filename = 'uploads/'+fname),
                               initial_sudoku = sudoku_grid, 
                               solved_sudoku = solved_grid)

    else:

        # this is rendered when the image can't be processed initially
        flash("Oops, I am having trouble processing your Sudoku!  Take a clearer photo and try again.")
        return redirect(url_for('sudokusolver'))
Exemplo n.º 21
0
 def check_row_test(self):
     grid = [[1, 2, 3, 4, 5, 6, 7, 8, 9], [2, 0, 0, 0, 0, 0, 0, 0, 0],
             [3, 3, 0, 0, 0, 0, 0, 0, 0], [4, 0, 0, 0, 0, 0, 0, 0, 0],
             [5, 0, 0, 0, 0, 0, 0, 0, 0], [6, 0, 0, 0, 0, 0, 0, 0, 0],
             [7, 0, 0, 0, 0, 0, 0, 0, 0], [8, 0, 0, 0, 0, 0, 0, 0, 0],
             [9, 0, 0, 0, 0, 0, 0, 0, 0]]
     s = Sudoku(grid)
     self.assertTrue(s.no_duplicates(grid[0]))
     self.assertTrue(s.no_duplicates(grid[1]))
     self.assertFalse(s.no_duplicates(grid[2]))
Exemplo n.º 22
0
    def ingresar_tamaño_tablero(self):#se ingresa el tamaño del tablero
        self.tamaño = 0
        while self.tamaño != "9" and self.tamaño != "4":
            self.tamaño = input("Ingrese el tamaño del tablero (4/9)\n")
            if self.tamaño != "9" and self.tamaño != "4":
                print("Ingrese el tamaño del tablero nuevamente\n")

        self.tamaño = int(self.tamaño)      
        self.board = api(int(self.tamaño))
        self.game = Sudoku(self.board)
Exemplo n.º 23
0
 def test_position_originals(self):
     self.table = ["53xx7xxxx", "6xx195xxx", "x98xxxx6x",
                   "8xxx6xxx3", "4xx8x3xx1", "7xxx2xxx6",
                   "x6xxxx28x", "xxx419xx5", "xxxx8xx79"]
     self.sudoku = Sudoku(self.table, 9)
     self.assertEqual(self.sudoku.ori_pos,
                      ["00", "01", "04", "10", "13", "14", "15", "21", "22",
                       "27", "30", "34", "38", "40", "43", "45", "48", "50",
                       "54", "58", "61", "66", "67", "73", "74", "75", "78",
                       "84", "87", "88"])
Exemplo n.º 24
0
 def test_Sudoku_Gano(self):
     sudoku = Sudoku([["4", "1", "3", "8", "2", "5", "6", "7", "9"],
                      ["5", "6", "7", "1", "4", "9", "8", "3", "2"],
                      ["2", "8", "9", "7", "3", "6", "1", "4", "5"],
                      ["1", "9", "5", "4", "6", "2", "7", "8", "3"],
                      ["7", "2", "6", "9", "8", "3", "5", "1", "4"],
                      ["3", "4", "8", "5", "1", "7", "2", "9", "6"],
                      ["8", "5", "1", "6", "9", "4", "3", "2", "7"],
                      ["9", "7", "2", "3", "5", "8", "4", "6", "1"],
                      ["6", "3", "4", "2", "7", "1", "9", "5", "8"]])
     self.assertTrue(sudoku.gano())
Exemplo n.º 25
0
 def test_Sudoku_Zona(self):
     sudoku = Sudoku([["5", "3", "x", "x", "x", "7", "x", "x", "x"],
                      ["6", "x", "x", "1", "9", "5", "x", "x", "x"],
                      ["x", "9", "8", "x", "x", "x", "x", "6", "x"],
                      ["8", "x", "x", "x", "6", "x", "x", "x", "3"],
                      ["4", "x", "x", "8", "x", "3", "x", "x", "1"],
                      ["7", "x", "x", "x", "2", "x", "x", "x", "6"],
                      ["x", "6", "x", "x", "x", "x", "2", "8", "x"],
                      ["x", "x", "x", "4", "1", "9", "x", "x", "5"],
                      ["x", "x", "x", "x", "8", "x", "x", "7", "9"]])
     self.assertFalse(sudoku.ingresar_numero(2, 2, 5))
Exemplo n.º 26
0
 def test_Sudoku_Perdio(self):
     sudoku = Sudoku([["5", "3", "x", "x", "x", "7", "x", "x", "x"],
                      ["6", "x", "x", "1", "9", "5", "x", "x", "x"],
                      ["x", "9", "8", "x", "x", "x", "x", "6", "x"],
                      ["8", "x", "x", "x", "6", "x", "x", "x", "3"],
                      ["4", "x", "x", "8", "x", "3", "x", "x", "1"],
                      ["7", "x", "x", "x", "2", "x", "x", "x", "6"],
                      ["x", "6", "x", "x", "x", "x", "2", "8", "x"],
                      ["x", "x", "x", "4", "1", "9", "x", "x", "5"],
                      ["x", "x", "x", "x", "8", "x", "x", "7", "9"]])
     self.assertFalse(sudoku.gano())
Exemplo n.º 27
0
 def test_Sudoku_Valores_Fijos(self):
     sudoku = Sudoku([["5", "3", "x", "x", "7", "x", "x", "x", "x"],
                      ["6", "x", "x", "1", "9", "5", "x", "x", "x"],
                      ["x", "9", "8", "x", "x", "x", "x", "6", "x"],
                      ["8", "x", "x", "x", "6", "x", "x", "x", "3"],
                      ["4", "x", "x", "8", "x", "3", "x", "x", "1"],
                      ["7", "x", "x", "x", "2", "x", "x", "x", "6"],
                      ["x", "6", "x", "x", "x", "x", "2", "8", "x"],
                      ["x", "3", "x", "4", "1", "9", "x", "x", "5"],
                      ["x", "x", "x", "x", "8", "x", "x", "7", "9"]])
     self.assertFalse(sudoku.ingresar_numero(0, 0, 1))
Exemplo n.º 28
0
 def find_options_test(self):
     grid = [[5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0],
             [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3],
             [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6],
             [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5],
             [0, 0, 0, 0, 8, 0, 0, 7, 9]]
     s = Sudoku(grid)
     self.assertEqual(s.find_options(0, 2), {1, 2, 4})
     self.assertEqual(s.find_options(4, 4), {5})
     self.assertEqual(s.find_options(5, 1), {1, 5})
     self.assertEqual(s.find_options(8, 6), {1, 3, 4, 6})
Exemplo n.º 29
0
 def test_Sudoku_Columna_2(self):
     sudoku = Sudoku([["5", "3", "x", "x", "x", "7", "x", "x", "x"],
                      ["6", "x", "x", "1", "9", "5", "x", "x", "x"],
                      ["x", "9", "8", "x", "x", "x", "x", "6", "x"],
                      ["8", "x", "x", "x", "6", "x", "x", "x", "3"],
                      ["4", "x", "x", "8", "x", "3", "x", "x", "1"],
                      ["7", "x", "x", "x", "2", "x", "x", "x", "6"],
                      ["x", "6", "x", "x", "x", "x", "2", "8", "x"],
                      ["x", "x", "x", "4", "1", "9", "x", "x", "5"],
                      ["x", "x", "x", "x", "8", "x", "x", "7", "9"]])
     self.assertFalse(sudoku.ingresar_numero(0, 8, 9))
Exemplo n.º 30
0
 def test_fill(self):
     sudoku = Sudoku(easy_grid)
     sudoku.fill()
     self.assertEqual(sudoku.solved, True)
     self.assertEqual(sudoku.feasible, True)
     original_values = True
     for i in range(sudoku.size):
         for j in range(sudoku.size):
             val = easy_grid[i][j]
             equal = (val == 0 or val == sudoku.grid[i][j])
             original_values = original_values and equal
     self.assertEqual(original_values, True)
Exemplo n.º 31
0
    def test_Sudoku_Ingrasar_valor_sobre_valor_fijo(self):

        sudoku = Sudoku([["5", "3", "x", "x", "x", "7", "x", "x", "x"],
                         ["6", "x", "x", "1", "9", "5", "x", "x", "x"],
                         ["x", "9", "8", "x", "x", "x", "x", "6", "x"],
                         ["8", "x", "x", "x", "6", "x", "x", "x", "3"],
                         ["4", "x", "x", "8", "x", "3", "x", "x", "1"],
                         ["7", "x", "x", "x", "2", "x", "x", "x", "6"],
                         ["x", "6", "x", "x", "x", "x", "2", "8", "x"],
                         ["x", "x", "x", "4", "1", "9", "x", "x", "5"],
                         ["x", "x", "x", "x", "8", "x", "x", "7", "9"]])

        self.assertFalse(sudoku.ingresar_valor(0, 0, 3))
Exemplo n.º 32
0
    def test_Sudoku_Repetido_en_Fila_1(self):

        sudoku = Sudoku([["5", "3", "x", "x", "x", "7", "x", "x", "x"],
                         ["6", "x", "x", "1", "9", "5", "x", "x", "x"],
                         ["x", "9", "8", "x", "x", "x", "x", "6", "x"],
                         ["8", "x", "x", "x", "6", "x", "x", "x", "3"],
                         ["4", "x", "x", "8", "x", "3", "x", "x", "1"],
                         ["7", "x", "x", "x", "2", "x", "x", "x", "6"],
                         ["x", "6", "x", "x", "x", "x", "2", "8", "x"],
                         ["x", "x", "x", "4", "1", "9", "x", "x", "5"],
                         ["x", "x", "x", "x", "8", "x", "x", "7", "9"]])

        self.assertFalse(sudoku.ingresar_valor(1, 3, 5))
Exemplo n.º 33
0
    def test_Sudoku_Repetido_en_Columna_3(self):

        sudoku = Sudoku([["5", "3", "x", "x", "7", "x", "x", "x", "x"],
                         ["6", "x", "x", "1", "9", "5", "x", "x", "x"],
                         ["x", "9", "8", "x", "x", "x", "x", "6", "x"],
                         ["8", "x", "x", "x", "6", "x", "x", "x", "3"],
                         ["4", "x", "x", "8", "x", "3", "x", "x", "1"],
                         ["7", "x", "x", "x", "2", "x", "x", "x", "6"],
                         ["x", "6", "x", "x", "x", "x", "2", "8", "x"],
                         ["x", "3", "x", "4", "1", "9", "x", "x", "5"],
                         ["x", "x", "x", "x", "8", "x", "x", "7", "9"]])

        self.assertFalse(sudoku.ingresar_valor(6, 4, 2))
Exemplo n.º 34
0
 def test_solve(self):
     sudoku = Sudoku(test_grid)
     solved = sudoku.solve()
     self.assertEqual(solved.valid, True)
     self.assertEqual(solved.feasible, True)
     self.assertEqual(solved.solved, True)
     original_values = True
     for i in range(sudoku.size):
         for j in range(sudoku.size):
             val = test_grid[i][j]
             equal = (val == 0 or val == solved.grid[i][j])
             original_values = original_values and equal
     self.assertEqual(original_values, True)
Exemplo n.º 35
0
 def test_sudoku_9x9(self):
     esperado = np.array( [[6, 7, 2, 1, 5, 4, 9, 3, 8],
                         [3, 5, 4, 2, 8, 9, 1, 6, 7],
                         [8, 1, 9, 3, 7, 6, 2, 5, 4],
                         [7, 2, 1, 6, 4, 3, 8, 9, 5],
                         [9, 4, 8, 5, 1, 2, 3, 7, 6],
                         [5, 6, 3, 8, 9, 7, 4, 1, 2],
                         [4, 8, 5, 7, 3, 1, 6, 2, 9],
                         [2, 3, 7, 9, 6, 8, 5, 4, 1],
                         [1, 9, 6, 4, 2, 5, 7, 8, 3]])
     sudoku = Sudoku(self.tablero_9x9)
     self.assertTrue(sudoku.solve_sudoku())
     self.assertEqual(esperado.any(),(sudoku.sudoku).any(),msg="Compara Resultado esperado con el resultado obtenido, True--> si son iguales, False-->si no lo son")
Exemplo n.º 36
0
class Interfaz():

    def ingresar_tamaño_tablero(self):#se ingresa el tamaño del tablero
        self.tamaño = 0
        while self.tamaño != "9" and self.tamaño != "4":
            self.tamaño = input("Ingrese el tamaño del tablero (4/9)\n")
            if self.tamaño != "9" and self.tamaño != "4":
                print("Ingrese el tamaño del tablero nuevamente\n")

        self.tamaño = int(self.tamaño)      
        self.board = api(int(self.tamaño))
        self.game = Sudoku(self.board)

    def ingresar_posicion(self, fila, columna, valor):  #se verifica que exista la posicion en la que la persona va a ingresar el valor

        if (fila > 0 and fila <= self.tamaño and columna > 0 and columna <= self.tamaño and valor > 0 and valor <= self.tamaño):
            return True
        else:
            return False
        
    def ingresar_valor(self, numero, x, y): 
        try:
            if int(x) > self.tamaño:
                return False
            elif int(y) > self.tamaño:
                return False
            elif numero != "x":
                if int(numero) > 0 and int(numero) < self.tamaño+1:
                    return True
            return True
        except Exception as w: 
            print(w)
            return False

    def pedir_valores(self):
        self.numero = input("Ingrese el valor")
        self.fila = input("Escoja fila")
        self.columna = input("Escoja columna")
        print("")

    def jugar(self):
        self.ingresar_tamaño_tablero()    
        print("")
        print(self.game.imprimir_tablero())
        while not self.game.win():
            self.pedir_valores()
            if self.ingresar_valor(self.fila, self.columna, self.numero):
                self.game.ingresar_valor(int(self.fila)-1, int(self.columna)-1, self.numero)
                print(self.game.imprimir_tablero())
            else:
                print("INGRESE UN VALOR CORRECTO")
Exemplo n.º 37
0
    def ingresar_dimension(self):
        self.tamaño = 0

        #Para ingresear la dimension del tablero
        while self.tamaño != "9" and self.tamaño != "4":
            self.tamaño = input("Ingrese el tamaño del tablero (4/9)\n")
            if self.tamaño != "9" and self.tamaño != "4":
                print(
                    "EL TAMAÑO DEL TABLERO NO ES CORRECTO \nIngrese el tamaño del tablero nuevamente...\n"
                )

        self.tamaño = int(self.tamaño)
        self.tablero = api(int(self.tamaño))
        self.game = Sudoku(self.tablero)
Exemplo n.º 38
0
 def __init__(self, nombre, dif = int):
     """
         Constructor de la clase Juego. Aquí se almacena toda la información
         correspondiente a un juego de sudoku.
         @param nombre, nombre del jugador.
         @param dif, dificultad del juego.
         @author Iván Aveiga
     """
     self.nombre = nombre
     self.dif = dif
     self.time = 0
     self.hints = 5
     self.juego = Sudoku() #tablero a jugar
     self.tablero = Sudoku()   #tablero lleno
     self.create(dif)
Exemplo n.º 39
0
    def setUp(self):
        self.sudoku9 = Sudoku([["5", "3", "x", "x", "7", "x", "x", "x", "x"],
                               ["6", "x", "x", "x", "9", "5", "x", "x", "x"],
                               ["x", "9", "8", "x", "x", "x", "x", "6", "x"],
                               ["8", "x", "x", "x", "6", "x", "x", "x", "3"],
                               ["4", "x", "x", "8", "x", "3", "x", "x", "1"],
                               ["7", "x", "x", "x", "2", "x", "x", "x", "6"],
                               ["x", "6", "x", "x", "x", "x", "2", "8", "x"],
                               ["x", "x", "x", "4", "1", "9", "x", "x", "5"],
                               ["x", "x", "x", "x", "8", "x", "x", "7", "9"]])

        self.sudoku4 = Sudoku([["4", "x", "3", "1"],
                               ["x", "3", "x", "x"],
                               ["3", "1", "x", "2"],
                               ["x", "4", "x", "x"]])
Exemplo n.º 40
0
 def setUp(self):
     self.sudoku = Sudoku([
         [8, 0, 0, 0, 5, 4, 0, 6, 0],
         [0, 9, 0, 0, 3, 2, 0, 0, 0],
         [0, 0, 4, 0, 6, 7, 0, 3, 1],
         [0, 0, 2, 7, 0, 0, 0, 0, 5],
         [4, 6, 0, 2, 0, 5, 0, 1, 8],
         [1, 0, 0, 0, 0, 8, 7, 0, 0],
         [2, 1, 0, 4, 8, 0, 9, 0, 0],
         [0, 0, 0, 5, 7, 0, 0, 4, 0],
         [0, 4, 0, 6, 2, 0, 0, 0, 3]
     ])
Exemplo n.º 41
0
 def setUp(self):
     self.sudoku = Sudoku([
         [2, 0, 6, 4, 0, 0, 0, 5, 3],
         [0, 0, 0, 2, 7, 5, 0, 9, 6],
         [5, 1, 7, 0, 3, 0, 0, 0, 4],
         [0, 3, 9, 8, 0, 0, 5, 1, 0],
         [7, 5, 0, 1, 0, 6, 3, 0, 0],
         [1, 0, 0, 0, 5, 3, 0, 6, 2],
         [0, 7, 0, 0, 6, 2, 4, 8, 0],
         [0, 0, 1, 3, 4, 0, 2, 0, 5],
         [4, 2, 8, 0, 1, 0, 6, 0, 0]
     ])
Exemplo n.º 42
0
 def setUp(self):
     self.sudoku = Sudoku([
         [0, 3, 5, 2, 9, 0, 8, 6, 4],
         [0, 8, 2, 4, 1, 0, 7, 0, 3],
         [7, 6, 4, 3, 8, 0, 0, 9, 0],
         [2, 1, 8, 7, 3, 9, 0, 4, 0],
         [0, 0, 0, 8, 0, 4, 2, 3, 0],
         [0, 4, 3, 0, 5, 2, 9, 7, 0],
         [4, 0, 6, 5, 7, 1, 0, 0, 9],
         [3, 5, 9, 0, 2, 8, 4, 1, 7],
         [8, 0, 0, 9, 0, 0, 5, 2, 6]
     ])
Exemplo n.º 43
0
 def setUp(self):
     self.sudoku = Sudoku([
         [0, 0, 0, 0, 5, 6, 4, 0, 0],
         [6, 0, 7, 0, 0, 1, 0, 8, 9],
         [0, 1, 0, 0, 0, 0, 0, 6, 0],
         [7, 2, 0, 3, 0, 9, 0, 5, 0],
         [1, 3, 0, 0, 6, 0, 0, 7, 2],
         [0, 9, 0, 1, 0, 7, 0, 4, 3],
         [0, 7, 0, 0, 0, 0, 0, 9, 0],
         [8, 5, 0, 9, 0, 0, 3, 0, 6],
         [0, 0, 1, 5, 8, 0, 0, 0, 0]
     ])
Exemplo n.º 44
0
class SudokuTestCase3(unittest.TestCase):

    """
    Tests the validity of the sudoku solver algorithms, in making sure that
    the solution puzzle that it obtains is correct
    """

    def setUp(self):
        self.sudoku = Sudoku([
            [8, 0, 0, 0, 5, 4, 0, 6, 0],
            [0, 9, 0, 0, 3, 2, 0, 0, 0],
            [0, 0, 4, 0, 6, 7, 0, 3, 1],
            [0, 0, 2, 7, 0, 0, 0, 0, 5],
            [4, 6, 0, 2, 0, 5, 0, 1, 8],
            [1, 0, 0, 0, 0, 8, 7, 0, 0],
            [2, 1, 0, 4, 8, 0, 9, 0, 0],
            [0, 0, 0, 5, 7, 0, 0, 4, 0],
            [0, 4, 0, 6, 2, 0, 0, 0, 3]
        ])

    def test_sudoku_valid_solution(self):
        self.sudoku.solve()
        solution = np.array([
            [8, 7, 3, 1, 5, 4, 2, 6, 9],
            [6, 9, 1, 8, 3, 2, 5, 7, 4],
            [5, 2, 4, 9, 6, 7, 8, 3, 1],
            [3, 8, 2, 7, 1, 6, 4, 9, 5],
            [4, 6, 7, 2, 9, 5, 3, 1, 8],
            [1, 5, 9, 3, 4, 8, 7, 2, 6],
            [2, 1, 6, 4, 8, 3, 9, 5, 7],
            [9, 3, 8, 5, 7, 1, 6, 4, 2],
            [7, 4, 5, 6, 2, 9, 1, 8, 3],
        ])
        equality = {i == j for i, j in zip(
            self.sudoku.puzzle.flatten(), solution.flatten())}
        self.assertTrue(True in equality and False not in equality)
Exemplo n.º 45
0
class SudokuTestCase(unittest.TestCase):

    """
    Tests the validity of the solve() method on the challenge problem to
    check whether the solved puzzle matches the correct solution
    """

    def setUp(self):
        self.sudoku = Sudoku([
            [0, 3, 5, 2, 9, 0, 8, 6, 4],
            [0, 8, 2, 4, 1, 0, 7, 0, 3],
            [7, 6, 4, 3, 8, 0, 0, 9, 0],
            [2, 1, 8, 7, 3, 9, 0, 4, 0],
            [0, 0, 0, 8, 0, 4, 2, 3, 0],
            [0, 4, 3, 0, 5, 2, 9, 7, 0],
            [4, 0, 6, 5, 7, 1, 0, 0, 9],
            [3, 5, 9, 0, 2, 8, 4, 1, 7],
            [8, 0, 0, 9, 0, 0, 5, 2, 6]
        ])

    def test_sudoku_puzzle_not_solved(self):
        self.assertFalse(self.sudoku.isSolved())

    def test_sudoku_puzzle_solved(self):
        self.sudoku.solve()
        self.assertTrue(self.sudoku.isSolved())

    def test_sudoku_valid_solution(self):
        self.sudoku.solve()
        solution = np.array([[1, 3, 5, 2, 9, 7, 8, 6, 4],
                             [9, 8, 2, 4, 1, 6, 7, 5, 3],
                             [7, 6, 4, 3, 8, 5, 1, 9, 2],
                             [2, 1, 8, 7, 3, 9, 6, 4, 5],
                             [5, 9, 7, 8, 6, 4, 2, 3, 1],
                             [6, 4, 3, 1, 5, 2, 9, 7, 8],
                             [4, 2, 6, 5, 7, 1, 3, 8, 9],
                             [3, 5, 9, 6, 2, 8, 4, 1, 7],
                             [8, 7, 1, 9, 4, 3, 5, 2, 6]])
        equality = {i == j for i, j in zip(
            self.sudoku.puzzle.flatten(), solution.flatten())}
        self.assertTrue(True in equality and False not in equality)
Exemplo n.º 46
0
class SudokuTestCase2(unittest.TestCase):

    """
    Tests the validity of the solve() method of the Sudoku class to
    make sure that the ending puzzle matches the correct solution
    """

    def setUp(self):
        self.sudoku = Sudoku([
            [0, 0, 0, 0, 5, 6, 4, 0, 0],
            [6, 0, 7, 0, 0, 1, 0, 8, 9],
            [0, 1, 0, 0, 0, 0, 0, 6, 0],
            [7, 2, 0, 3, 0, 9, 0, 5, 0],
            [1, 3, 0, 0, 6, 0, 0, 7, 2],
            [0, 9, 0, 1, 0, 7, 0, 4, 3],
            [0, 7, 0, 0, 0, 0, 0, 9, 0],
            [8, 5, 0, 9, 0, 0, 3, 0, 6],
            [0, 0, 1, 5, 8, 0, 0, 0, 0]
        ])

    def test_sudoku_solved(self):
        self.sudoku.solve()
        self.sudoku.isSolved()

    def test_sudoku_valid_solution(self):
        self.sudoku.solve()
        solution = np.array([
                            [2, 8, 9, 7, 5, 6, 4, 3, 1],
                            [6, 4, 7, 2, 3, 1, 5, 8, 9],
                            [3, 1, 5, 4, 9, 8, 2, 6, 7],
                            [7, 2, 6, 3, 4, 9, 1, 5, 8],
                            [1, 3, 4, 8, 6, 5, 9, 7, 2],
                            [5, 9, 8, 1, 2, 7, 6, 4, 3],
                            [4, 7, 3, 6, 1, 2, 8, 9, 5],
                            [8, 5, 2, 9, 7, 4, 3, 1, 6],
                            [9, 6, 1, 5, 8, 3, 7, 2, 4],
                            ])
        equality = {i == j for i, j in zip(
            self.sudoku.puzzle.flatten(), solution.flatten())}
        self.assertTrue(True in equality and False not in equality)
Exemplo n.º 47
0
def parse_grid(s):
    """Parse a grid from a string.

    Assumes the string reads the grid line by line,
    and contains 81 numerical characters.
    """
    s = s.strip()
    if not (len(s) == 81 and s.isdigit()):
        raise Exception("The grid does not have the right length or contains" +
                        " non-number characters.")
    return [map(int, list(s[i:i+9])) for i in range(0, len(s), 9)]

if __name__ == '__main__':
    parser = ArgumentParser(description="Solve a Sudoku.")
    parser.add_argument('grid',
                        help="The grid, read line by line as a string of 81 " +
                             "numerical characters. Zeroes represent empty '" +
                             "cells.")
    grid = parse_grid(parser.parse_args().grid)
    sdk = Sudoku(grid)
    print "\n-- original grid -- \n"
    print sdk
    print "-- solved grid -- \n"
    t_ini = time.time()
    solved = sdk.solve()
    t_end = time.time()

    print solved
    print "solved in %.2f sec." % (t_end - t_ini)
Exemplo n.º 48
0
 def test_sudoku_son(self):
     sudoku = Sudoku(test_grid)
     son = sudoku.sudoku_son(1, 2, 3)
     self.assertEqual(son.grid[1][2], 3)
Exemplo n.º 49
0
def sudokuMasSolve(level):
    s = Sudoku(level)
    return s.asd()
Exemplo n.º 50
0
def getSudoku(level):
   s = Sudoku(level)
   return s.toSudokubumSemilla()
Exemplo n.º 51
0
        supported action: \n\
            * print: print in console the sudoku values \n\
            * solve: solve the sudoku \n\
            * generate: generate a new sudoku puzzle")


sudo = None

for arg in sys.argv[1::2]:
    idx = sys.argv.index(arg) + 1
    if len(sys.argv) <= idx:
        raise Exception("Specify a value for the action : " + arg)

    argvalue = sys.argv[idx]
    if arg == "-n":
        sudo = Sudoku(int(argvalue))

    if arg == "-v":
        index = 0
        cells_number = sudo.dimension ** 2
        for value in str(argvalue).split(","):
            x = index // cells_number
            y = index - ((index // cells_number) * cells_number)
            sudo.set_value(x, y, value)
            index += 1

    if arg == "-a":
        if argvalue == "print":
            sudo.print()
        elif argvalue == "solve":
            sudo.print()
Exemplo n.º 52
0
        :return: priority list of (([list of node solutions],row<int>,column<int>))
        """
        onesList = oldSudoku.getDepthOf(1)
        totalList = []
        totalList.extend(onesList)
        for i in list(range(1+1,oldSudoku.getSize()+1)):
            totalList.extend(oldSudoku.getDepthOf(i))
        return totalList

    def _SmallestToLargetList(self, oldSudoku):
        totalList = []
        for i in xrange(oldSudoku.getSize()+1):
            totalList.extend(oldSudoku.getDepthOf(i))
        return totalList


class DeadEndError(Exception):
    """ NODE Exception Class """
    def __init__(self,value):
        self.value = value
    def __str__(self):
        return repr(self.value)





print "Starting"
s = Sudoku.Sudoku(9,Sudoku.makeSudokuBoard('Sudoku/Board01.txt'))
solver = SudokuCSP(s)
solver.solve()
Exemplo n.º 53
0
 def test_check_square(self):
     sudoku = Sudoku(test_grid)
     for i in range(sudoku.size):
         self.assertEqual(sudoku.check_square(i), True)
Exemplo n.º 54
0
 def test_find_disjunction(self):
     sudoku = Sudoku(test_grid)
     i, j, l = sudoku.find_disjunction()
     self.assertEqual(i, 2)
     self.assertEqual(j, 8)
     self.assertEqual(l, [5, 7])
Exemplo n.º 55
0
def solve_puzzle(p):
    c = Sudoku(p)
    c.solve_board()
    return c.board_to_list()
import base64
from Sudoku import Sudoku

s = Sudoku()

#s.generate()

s.setValues([
    [0, 7, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 3, 5, 9, 0, 2],
    [0, 0, 5, 0, 0, 0, 0, 3, 0],
    [0, 0, 0, 0, 6, 1, 0, 0, 7],
    [0, 0, 8, 0, 4, 0, 0, 0, 1],
    [0, 0, 9, 0, 0, 0, 0, 0, 0],
    [1, 0, 3, 6, 0, 0, 2, 5, 8],
    [0, 0, 7, 0, 0, 0, 3, 0, 0],
    [5, 6, 0, 2, 0, 0, 0, 0 ,0]
])

s.resolve()

#s.setValues([
#    [0, 2, 7, 0, 0, 0, 4, 3, 8],
#    [0, 0, 8, 4, 5, 0, 0, 0, 9],
#    [9, 0, 1, 0, 0, 2, 0, 6, 5],
#
#    [7, 0, 0, 0, 0, 6, 0, 0, 0],
#    [0, 0, 6, 3, 9, 8, 0, 1, 7],
#    [0, 0, 0, 0, 4, 0, 9, 0, 0],
#
#    [2, 0, 4, 1, 6, 0, 0, 0, 0],
Exemplo n.º 57
0
 def test_possible_values(self):
     sudoku = Sudoku(test_grid)
     self.assertEqual(sudoku.possible_values(0, 0), [3, 4, 5, 7, 9])
Exemplo n.º 58
0
def main():
	
	num_of_flags = len(argv) -1
	
	sudoku = Sudoku();
	
	if num_of_flags > 0:
		
		if '-' in argv[1]:		# is correct flag
			flag = argv[1]
			flag = flag[1:]
			
			if FROM_FILE_TO_FILE == flag:		# flag -f
				if num_of_flags > 2:
					if  not sudoku.init_from_file(argv[2]):
						exit("File " + argv[2] + " not exist.")
					try:
						f = open(argv[3], "w")
					except(IOError):
						exit("File error.")					
				else:
					if  not sudoku.init_from_file():
						exit("File sudoku.txt not exist.");
					try:
						f = open("answer.txt", "w")
					except(IOError):
						exit("File error.")
				st = time.time()
				answer = Sudoku.format_sudoku_answer( sudoku.solve() )
				f.write(answer)
				print "Time elapsed: {0} s. ".format(time.time() - st)	
				
			elif FROM_CONST_TO_FILE == flag:  	# flag -c
				sudoku.init_from_string(SUDOKU)
				st = time.time()
				answer = Sudoku.format_sudoku_answer( sudoku.solve() )
				if num_of_flags > 1:
					try:
						f = open(argv[2], "w")
					except(IOError):
						exit("File error.")
				else:
					try:
						f = open("answer.txt", "w")
					except(IOError):
						exit("File error.")
				f.write(answer)
				print "Time elapsed: {0} s. ".format(time.time() - st)	
				
			elif FROM_FILE_TO_DISLAY == flag:		# flag -d
				if num_of_flags > 1:
					if  not sudoku.init_from_file(argv[2]):
						exit("File " + argv[2] + " not exist.");
				else:
					if  not sudoku.init_from_file():
						exit("File sudoku.txt not exist.");
				st = time.time()
				answer = Sudoku.format_sudoku_answer( sudoku.solve() )
				print "ANSWER:\n", answer
				print "Time elapsed: {0} s. ".format(time.time() - st)

			elif FROM_CONST_TO_DISPALY == flag:		# flag -e
				sudoku.init_from_string(SUDOKU)
				st = time.time()
				answer = Sudoku.format_sudoku_answer( sudoku.solve() )
				print "ANSWER:\n", answer
				print "Time elapsed: {0} s. ".format(time.time() - st)
				
			elif HELP[0] == flag or HELP[1] == flag:
				display_help();
			else:
				exit("Incorect flag. Use SudokuSolver.py -help")
		else:
				exit("Incorect flag. Use SudokuSolver.py -help")
	else:
		if not sudoku.init_from_file():
			exit("File sudoku.txt not exist.");
		try:
			f = open("answer.txt", "w")
		except(IOError):
			exit("File error.")
		st = time.time()
		answer = Sudoku.format_sudoku_answer( sudoku.solve() )
		f.write(answer)
		print "Time elapsed: {0} s. ".format(time.time() - st)	
	return 0
Exemplo n.º 59
0
    parser.add_option(
        '-i', '--input-file', action="store", type="string",
        dest="inputFile",
        help="Specify file where sudoku puzzle is stored")
    parser.add_option('-o', '--output-file', action='store', type="string",
                      dest="outputFile",
                      help="Specify a file to store the solved sudoku")
    parser.add_option('-v', '--verbose', action="store_true", dest="verbose",
                      help="For a verbose output of the solving process")
    (options, args) = parser.parse_args()
    if options.inputFile is None:
        parser.print_help()
    else:
        # Get file contents
        sudokuPuzzle = SudokuIO.readFromFile(options.inputFile)
        # Initialize Sudoku solver
        sudoku = Sudoku(sudokuPuzzle)
        #Verbose output
        if options.verbose:
            print("Initial Puzzle")
            print(sudoku.puzzle)
        # Call to solve method
        sudoku.solve()
        # Verbose output
        if options.verbose:
            print("Solved puzzle")
        print(sudoku.puzzle)
        # if -o option selected
        if options.outputFile:
            SudokuIO.writeToFile(sudoku.puzzle, options.outputFile)