コード例 #1
0
ファイル: driver.py プロジェクト: leyulin/CS550
def play():
    #  get from sudoku.py
    easy1 = '..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3..'
    harder1 = '4173698.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......'

    for puzzle in [easy1, harder1]:
        # for puzzle in [easy1]:
        s = Sudoku(puzzle)
        # Initial sudoku state
        print("\nInitial problem:")
        s.display(s.infer_assignment())

        # The state of the puzzle after running AC3.
        AC3(s)
        if s.goal_test(s.curr_domains):
            print("\nAfter AC3 constraint propagation\n")
            s.display(s.infer_assignment())

        # if goal test fail try to find solution
        elif not s.goal_test(s.curr_domains):
            # run back track search
            solution = backtracking_search(s, select_unassigned_variable=mrv)
            if solution:
                print("\nSolved using backtracking:")
                s.display(s.infer_assignment())
            else:
                print("\nCould not be solved using backtrack\n")
                s.display(s.infer_assignment())
    def test_ac3(self):
        for puzzle in [easy1, harder1]:
            s = Sudoku(puzzle)  # construct a Sudoku problem
            s.display(s.infer_assignment())
            print("\n")

            AC3(s)
            s.display(s.infer_assignment())

            if s.goal_test(s.curr_domains):
                print("\nProblem was solved by AC3\n")
            else:
                print("\nProblem was not solved by AC3. Start searching ...\n")
コード例 #3
0
ファイル: driver.py プロジェクト: acfromspace/academia
def game():
    print("================================= Sudoku ==================================")
    print("CS 550 Artificial Intelligence | Prof. Roch | Assignment 4 | kingofthenorth")
    print("============================= Creating game... ============================")

    game_start = time.time()

    for puzzle in [easy1, harder1]:

        # Creates an instance of the puzzle to work with
        s = Sudoku(puzzle)

        # Creates a viewable interface of the working sudoku puzzle
        print("\nInitial problem:")
        s.display(s.infer_assignment())

        # Applies the AC3 constraint
        AC3(s)
        print("\nAfter AC3 constraint propagation applied!")

        # Keeps track of time of the puzzle
        puzzle_start = time.time()

        # If goal is not reached yet, keep trying to find a solution
        if not s.goal_test(s.curr_domains):
            print("\nBacktracking search starting...")
            result = backtracking_search(s, select_unassigned_variable=mrv)
            if result:
                # Success
                print("\nBacktracking solution:")
                s.display(s.infer_assignment())
            else:
                # Failure
                print("\nBacktracking failed! :(")

        current = time.time()

        # Time information to be relayed
        print("\nPuzzle time: {} | Overall time: {}".format(
            elapsed(puzzle_start, current), elapsed(game_start, current)))
コード例 #4
0
from csp_lib.sudoku import (Sudoku, easy1, harder1)
from constraint_prop import AC3
from backtrack import backtracking_search
from csp_lib.backtrack_util import mrv, mac

easy_puzzle = Sudoku(easy1)
easy_puzzle.display(easy_puzzle.infer_assignment())
print(AC3(easy_puzzle))
easy_puzzle.display(easy_puzzle.infer_assignment())


hard_puzzle = Sudoku(harder1)
hard_puzzle.display(hard_puzzle.infer_assignment())
print(AC3(easy_puzzle))
result = backtracking_search(hard_puzzle, select_unassigned_variable=mrv, inference=mac)
#print("result = " + str(result))
hard_puzzle.display(hard_puzzle.infer_assignment())



#easy_puzzle.display(easy_puzzle.infer_assignment())
'''
print("\n")
print("Domains Stuff")
print("print(easy_puzzle.domains)")
print(easy_puzzle.domains)
print("print(len(easy_puzzle.domains))")
print(len(easy_puzzle.domains))
print("print(type(easy_puzzle.domains[0]))")
print(type(easy_puzzle.domains[0]))
print("print(type(easy_puzzle.domains[2]))")
コード例 #5
0
def mac(csp, var, value, assignment, removals):
    """Maintain arc consistency."""
    return AC3(csp, [(X, var) for X in csp.neighbors[var]], removals)
コード例 #6
0
ファイル: driver.py プロジェクト: tpaulus/CS550

def is_solved(sudoku: Sudoku):
    for var in sudoku.curr_domains:
        if len(sudoku.curr_domains[var]) is not 1:
            return False
    return True


if __name__ == "__main__":
    for puzzle in [easy1, harder1]:
        # for puzzle in [easy1]:
        s = Sudoku(puzzle)  # construct a Sudoku problem
        print("New Sudoku Puzzle")
        s.display(s.infer_assignment())
        AC3(s)
        if is_solved(s):
            print("Solved via AC3")
            s.display(s.infer_assignment())
        else:
            print("Could not solve via AC3: Current Puzzle")
            s.display(s.infer_assignment())
            print("Trying to solve via Back Track")
            backtracking_search(s, inference=forward_checking, order_domain_values=lcv, select_unassigned_variable=mrv)
            if is_solved(s):
                print("Solved via Back Track")
                s.display(s.infer_assignment())
            else:
                print("Puzzle could not be solved: Current State")
                s.display(s.infer_assignment())
コード例 #7
0
def mac(csp, var, value, assignment, removals):
    """Maintain arc consistency.
    mac populates the queue to only look at the neighbors of the variable that we are assigning."""
    return AC3(csp, [(X, var) for X in csp.neighbors[var]], removals)
コード例 #8
0
from csp_lib.sudoku import (Sudoku, easy1, harder1)
from constraint_prop import AC3
from csp_lib.backtrack_util import mrv, lcv, mac
from backtrack import backtracking_search

for puzzle in [easy1, harder1]:
    sudoku_instance = Sudoku(puzzle)

    print("We have the following Sudoku puzzle to solve:", end="\n\n")
    sudoku_instance.display(sudoku_instance.infer_assignment())
    print("\nStarting constraint propagation (AC3) algorithm.")
    AC3(sudoku_instance)
    print("AC3 algorithm was successfully completed.")

    if sudoku_instance.goal_test(sudoku_instance.curr_domains):
        print("Problem was solved by AC3. Here is the solution:", end="\n\n")
        sudoku_instance.display(sudoku_instance.infer_assignment())
        print()
    else:
        print("Problem was not solved by AC3. Here is how it looks like:",
              end="\n\n")
        sudoku_instance.display(sudoku_instance.infer_assignment())
        print()
        print("We should start searching ...")
        search_result = backtracking_search(sudoku_instance, mrv, lcv, mac)
        print("Search has been completed successfully.")
        if sudoku_instance.goal_test(search_result):
            print("Given constraint satisfaction problem has been "
                  "successfully solved by backtracking search algorithm. Here "
                  "it the solution:", end='\n\n')
            sudoku_instance.display(sudoku_instance.infer_assignment())
コード例 #9
0
from constraint_prop import AC3
from csp_lib.backtrack_util import mrv, forward_checking, lcv, mac
from backtrack import backtracking_search

first = True

for puzzle in [easy1, harder1]:
    if first:
        s = Sudoku(puzzle)  # construct a Sudoku problem easy1
        print("Initial State easy")
        print()
        s.display(s.infer_assignment())
        print()
        print('Solving the problem...')
        print()
        AC3(s)
        s.display(s.infer_assignment())
        print()
        first = False
    else:
        h = Sudoku(puzzle)  # construct a Sudoku problem hard1
        print("Initial State hard")
        print()
        h.display(h.infer_assignment())
        print()
        print('Solving the problem. Apply AC3...')
        print()
        AC3(h)
        print()
        for var in h.curr_domains:
            h.curr_domains[var] = list(h.domains[var])
コード例 #10
0
ファイル: driver.py プロジェクト: nibichua/CS550_A4
from csp_lib.sudoku import (Sudoku, easy1, harder1)
from constraint_prop import AC3
from csp_lib.backtrack_util import mrv
from backtrack import backtracking_search

for puzzle in [easy1]:
    easy = Sudoku(easy1)  # constructing the easy Sudoku problem
    print("Easy Sudoku Problem:")
    easy.display(easy.infer_assignment())

    AC3(easy)  #Calling Constraint Propagation to solve

    print("\n")
    print("After calling AC3:")
    easy.display(easy.infer_assignment())

    if not easy.goal_test(easy.curr_domains):
        print("\n")
        print("Backtracking easy problem...")
        result = backtracking_search(easy, select_unassigned_variable=mrv)
        if result:
            print("After backtracking:")
            easy.display(easy.infer_assignment())

for puzzle in [harder1]:
    hard = Sudoku(puzzle)  # constructing the hard Sudoku problem
    print("\n")
    print("Hard Sudoku Problem:")
    hard.display(hard.infer_assignment())

    AC3(hard)  #Calling Constraint Propagation to solve
コード例 #11
0
from csp_lib.sudoku import (Sudoku, easy1, harder1)
from constraint_prop import AC3
from csp_lib.backtrack_util import mrv, mac
from backtrack import backtracking_search
import queue

for puzzle in [easy1, harder1]:
    s = Sudoku(puzzle)  # construct a Sudoku problem
    s.display(s.infer_assignment())
    constraints_satisfied = AC3(
        s
    )  # returns true or false This is to trigger Backtrack_search, Revise alters domains
    if constraints_satisfied is True:  # goal test instead
        solved = backtracking_search(csp=s,
                                     select_unassigned_variable=mrv,
                                     inference=mac)
        if solved is not None:
            print("backtrack search solution:")
            s.display(s.infer_assignment())
        else:
            print("This sudoku puzzle is not solvable")
    else:
        s.display(
            s.infer_assignment()
        )  # will display an updated board, because e was manipulated inside algorithm using revise def
        # or do I test to see if its solved, # goalstate
'''Output
. . 3 | . 2 . | 6 . .
9 . . | 3 . 5 | . . 1
. . 1 | 8 . 6 | 4 . .
------+-------+------
コード例 #12
0
ファイル: driver.py プロジェクト: bernicetuazon/ai-sudoku
'''

#all modules in csp_lib were created by Prof. Marie Roch from San Diego State University
from csp_lib.sudoku import (Sudoku, easy1,
                            harder1)  #import easy and hard starting puzzles
from csp_lib.backtrack_util import (mrv, forward_checking)

from backtrack import backtracking_search
from constraint_prop import AC3

for puzzle in [easy1, harder1]:
    s = Sudoku(puzzle)  # construct a Sudoku problem
    s.display(s.infer_assignment())  #print the initial game
    print("\n")

    if AC3(s):  #first try using AC-3 to solve the puzzle
        if s.goal_test(s.curr_domains):  #easy1 puzzle
            print("Congratulations, easy game is solved!")
            s.display(s.infer_assignment())  #display solved puzzle
            print("\n")
        else:  #harder1 puzzle
            #solve with backtracking search and by using the minimum-remaining-values heuristic
            #to choose the next unassigned variable
            solved = backtracking_search(s,
                                         select_unassigned_variable=mrv,
                                         inference=forward_checking)
            if solved is None:  #backtracking_search failed
                print("Puzzle cannot be solved by AC-3 or back tracking.\n")
            else:
                print("Congratulations, hard game is solved!")
                s.display(s.infer_assignment())  #display solved puzzle