Esempio n. 1
0
 def __str__(self):
     s = self.description + ""
     if self.filled_cell:
         s += "\nUpdated cell: " + str(self.filled_cell)
     if self.updated_cells:
         s += "\nRemoved candidates: " + str(self.updated_cells)
     if self.additional:
         s += "\n" + str(self.additional)
     if self.board:
         s += "\n" + SudokuPuzzle.get_pretty_matrix_string(self.board)
     if not self.filled_cell and self.updated_cells:
         s += "\n" + SudokuPuzzle.get_pretty_matrix_string(self.possibilities)
     return s
Esempio n. 2
0
def solve_step():
    try:
        board = request.json['board']
        puzzle_name = request.json['puzzleName']
        sp = SudokuPuzzle(board)
        # Check if the puzzle has a solution
        validate_puzzle(puzzle_name, board)

        # Solve the next step
        spStep = SudokuPuzzle(board)
        ssStep = SudokuSolver(spStep)
        ssStep.solve_next_step()
        log = ssStep.sudoku_logger.sudoku_log
        return jsonify({
            'success': True,
            'board': ssStep.sudoku_puzzle.get_board(),
            'steps_log': log
        })
    except Exception as e:
        print(e)
        return jsonify({
            'success': False
        })
Esempio n. 3
0
 def puzzle(cls, desc=None, rows=None, grows=None, cols=None, gcols=None):
     """ Start processing of puzzle
     :returns:  False if not processing this game
     """
     SlTrace.lg(
         f"puzzle(desc={desc}, rows={rows}, grows={grows} cols={cols} gcols={gcols})"
     )
     cls.desc = desc
     cls.rows = rows
     cls.grows = rows
     cls.cols = cols
     cls.gcols = gcols
     cls.cur_row = 0
     cls.sudoku_puzzle = SudokuPuzzle(desc=desc,
                                      rows=rows,
                                      grows=grows,
                                      cols=cols,
                                      gcols=gcols)
     if SlTrace.trace("puzzle_load"):
         cls.sudoku_puzzle.display("puzzle() start")
Esempio n. 4
0
def calculate_possibilities():
    board = request.json['board']
    sp = SudokuPuzzle(board)
    return jsonify({'possibilities': sp.get_possibilities()})
Esempio n. 5
0
def clear_board():
    puzzle = SudokuPuzzle(rows=gb.nRow, cols=gb.nCol, grows=gb.nSubRow, gcols=gb.nSubCol,
                          desc="Internal Puzzle")
    set_puzzle(puzzle)
Esempio n. 6
0
def use_puzzle(puzzle=None):
    """ Use Precreated puzzle
    Set reset_data to this
                # Pattern
                    Default: PZ1
                    n x n lines
                     - or numeric contents
    """
    ###global gb.o_data, gb.nCol, gb.nSubCol, gb.nRow, gb.nrowGroup, gb.o_board, gb.Initial_data, gb.nRow, gb.nCol
    
# Test puzzles 
    PZ1 = """
        -    2    -    -
        1    4    -    -
        -    -    3    2
        -    -    1    -
    """
    
    PZ2 = """
        3    2    4    1
        1    4    2    3
        4    1    3    2
        2    3    1    4
    """
    
    PZ3 = """
        -    2    4    1
        1    4    2    3
        4    1    3    2
        2    3    1    4
    """
    
    PZ4 = """
        -    -    4    1
        1    4    2    3
        4    1    3    2
        2    3    1    4
    """
    
    
    if puzzle is None:
        puzzle = PZ1
        puzzle = PZ2
        puzzle = PZ3
        puzzle = PZ4
        puzzle = PZ1
    nrow = 0
    ncol = 0
    rowcols = []            # array of rows of cols
    lines = puzzle.split("\n")
    lineno = 0
    for line in lines:
        lineno += 1
        m = re.match(r'^([^#]*)#', line)   # Remove comments
        if m:
            line = m.group(1)
        m = re.match(r'^\s+(.*)$', line)
        if m:
            line = m.group(1)
        m = re.match(r'^(.*)\s+$', line)
        if m:
            line = m.group(1)
        if re.match(r'^\s*$', line):     # Ignore blank lines
            continue
        
        nrow += 1
        cs = line.split()
        if ncol > 0 and len(cs) < ncol:
            raise SelectError("cols not identical in line: lineno")

        if len(cs) > ncol:
            ncol = len(cs) 
        rowcols.append(cs)

    if ncol != nrow:
        raise SelectError(f"number of cols{ncol} != number of rows{nrow}")
    gb.nRow = nrow
    gb.nCol = ncol
    gb.nSubCol = int(sqrt(gb.nCol))
    gb.nSubRow = int(sqrt(gb.nRow))
    
    puzzle = SudokuPuzzle(rows=nrow, cols=ncol, grows=gb.nSubRow, gcols=gb.nSubCol,
                          desc="Internal Puzzle")
    for ri in range(nrow):
        row = ri+1
        for ci in range(ncol):
            col = ci+1
            val = rowcols[ri][ci]
            if val == '-':
                continue         # Empty cell
            
            puzzle.add_cell(row=row, col=col, val=int(val))
    set_puzzle(puzzle)
Esempio n. 7
0
			msg = "Incorrect number of columns on line "+str(line_nr)+" (must have 9 columns)"
			sys.stderr.write("Error: " + msg + "\n")
			sys.exit(-1)
		except IOError:
			msg = "File ended before finishing a Su Doku table on line " + str(line_nr)
			sys.stderr.write("Error: " + msg + "\n")
			sys.exit(-2)
		except ValueError:
			msg = "Invalid value for a column detected on line " + str(line_nr)
			sys.stderr.write("Error: Invalid value for a column detected (numbers must be between 0 and 9)\n")
			sys.exit(-3)
		else:
			sudoku_table.append(sudoku_line)
			line_nr+=1

	sudoku = SudokuPuzzle(sudoku_table)

	sudoku.set_log(args.verbose,args.output)

	args.output.write("Game " + str(game) + "\n" + str(sudoku))

	sudoku.fill_unique_spots()

	sudoku.exhaustive_search()

	args.output.write("Solution:\n" + str(sudoku))
	game+=1	

	# try reading a blank line, if it doesn't, then all games were processed
	try:
		blank=args.input.readline()
Esempio n. 8
0
def get_solution(puzzle_name, board):
    print("ACTUALLY SOLVING")
    sp = SudokuPuzzle(board)
    ss = SudokuSolver(sp)
    ss.do_work()
    return ss.sudoku_puzzle.get_board()