Beispiel #1
0
def bfs(problem):
	start_time = time.time()
	#print("next problem")
	search.breadth_first_tree_search(problem)
	#problem.display(problem.infer_assignment())
	csp.AC3(problem)
	#problem.display(problem.infer_assignment())
	solution = problem.infer_assignment()
	end_time = time.time()
	elapsed_time = end_time-start_time
	file_sudoku_print("BFS", elapsed_time, solution)
  def solve_fn(self):
    # make a copy of the puzzle to determine the moves
    sp = Sliding_puzzle(self.n, # number of rows
                        self.m, # number of columns
                        goal = list(range(1, self.m*self.n))+[0] ,
                        initial = self.board)
    # sol_ts : goal leaf node of the solution tree search
    print ('** Starting the breadth_first_tree_search **')
    t0 = time.time()
    sol_ts = search.breadth_first_tree_search(sp)
##    sol_ts = breadth_first_search_v0(sp)
    t1 = time.time()
    sp.print_solution(sol_ts)
    print ("Solver took ",t1-t0, ' seconds')

    # The actions are 'U','D','L' and 'R'  (move the blank tile up, down, left  right)
    # b = self.board.index(0) # position index of the blank tile
    # p = b + offsetDict[cmd]  is the index of the tile to move 
    offsetDict = {'U':-self.m, 'D':self.m, 'L':-1 , 'R':1} 
    for node in sol_ts.path():
      if node.action: # root action is None and should be skipped
        assert node.action in ['U','D','L','R']
        p = self.board.index(0) + offsetDict[node.action]
        self.move(p)
        while self.moving is not None:
          time.sleep(0.1)
    self.solve_button.configure(text='Solve', command=self.solve)
Beispiel #3
0
def sudokuSolver(line,algor):
    puzzle = csp.Sudoku(line)
    puzzle.display(puzzle.infer_assignment())

    if search != "backtracking":
        if len(line) == 16:
            size = 4
        else:
            size = 9
    board = []
    c = 0
    for i in range(size):
        board.append([0]*size)
        for j in range(size):
            if line[c] == '.':
                board[i][j] = 0
            else:
                board[i][j] = int(line[c])
            c = c+1

    if len(line) == 16:
        sudoku = search.Problem(board,[1,2,3,4])
    else:
        sudoku = search.Problem(board,[1, 2, 3, 4, 5, 6, 7, 8, 9])
    if algor == "bfs":
        pie = search.breadth_first_tree_search(sudoku)
    else:
        pie = search.depth_first_tree_search(sudoku)
    for row in pie.state:
        print(row)
def main():
    problem = MissionariesAndCannibals([3, 3, 0], [0, 0, 1])
    startTime = time.time()
    result = breadth_first_tree_search(problem)
    #result = depth_first_tree_search(problem)
    endTime = time.time()
    print('걸린 시간 : ', endTime - startTime)
    printPathAndSolution(result)
Beispiel #5
0
def huarong_pass_search(desired_search_strategy):
    """The function returns a list of actions that when applied to the initial state lead to the goal
    state."""
    initTime = datetime.datetime.now()
    problem = HuarongPass()
    if desired_search_strategy == "BFS":
        s = search.breadth_first_tree_search(problem)
    elif desired_search_strategy == "DFS":
        s = search.depth_first_graph_search(problem)
    elif desired_search_strategy == "IDS":
        s = search.iterative_deepening_search(problem)
    else:
        print "Desired search strategy not found!"
    endTime = datetime.datetime.now()
    print "Time taken", endTime - initTime
    return s.solution()
def main():
    # ----------------------------------- Water Jug Problem -------------------------------------- #

    water_jug_prob = P1.WaterJugProblem((0, 0), (2, 0), (4, 3))

    t0 = time.time()
    src1 = search.breadth_first_tree_search(water_jug_prob)

    t1 = time.time()
    src2 = search.astar_search(water_jug_prob)

    dt2 = time.time() - t1
    dt1 = t1 - t0

    print(src1.solution())
    print(src2.solution())

    print(
        "Uninformed search time: {0:.4f} seconds\nInformed search time: {1:.4f} seconds"
        .format(dt1, dt2))

    # -------------------------------------------------------------------------------------------- #

    # ----------------------------------- N-Puzzle Problem: -------------------------------------- #

    puzzle_prob = P2.NPuzzleProblem((5, 1, 2, 4, 7, 6, 3, 8, 9, 14, 10, 12, 13, 0, 11, 15), \
        (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0), 4)

    t0 = time.time()
    src1 = search.astar_search(puzzle_prob, puzzle_prob.h1)

    t1 = time.time()
    src2 = search.astar_search(puzzle_prob, puzzle_prob.h2)

    dt2 = time.time() - t1
    dt1 = t1 - t0

    print(src1.solution())
    print(src2.solution())

    print(
        "Heuristic 1 search time: {0:.4f} seconds\nHeuristic 2 search time: {1:.4f} seconds"
        .format(dt1, dt2))
def solve_sokoban_elem(warehouse):
    '''    
    This function should solve using elementary actions 
    the puzzle defined in a file.
    
    @param warehouse: a valid Warehouse object
    @return
        A list of strings.
        If puzzle cannot be solved return ['Impossible']
        If a solution was found, return a list of elementary actions that solves
            the given puzzle coded with 'Left', 'Right', 'Up', 'Down'
            For example, ['Left', 'Down', Down','Right', 'Up', 'Down']
            If the puzzle is already in a goal state, simply return []

    '''
    #if SokobanPuzzle(warehouse).goal_test(warehouse.boxes):
    #   return []
    
    steps = breadth_first_tree_search(SokobanPuzzle(warehouse))
    
    #if check_action_seq(warehouse, steps.actions()) is "Failure":
    #    return "Impossible"
    return steps
    '''
Beispiel #8
0
def sudokuSolver(grid, algorithm):
    sudoku = Sudoku2(grid)
    f = open("sudoku.txt", "w")

    if algorithm == "bfs":
        inittime = time.time()
        info = search.breadth_first_tree_search(sudoku)
        finaltime = time.time()
        solution = sudoku.display(dict(info[0].state))
        f.write("BFS Algorithm Solution For " + grid + ":\n")
        f.write(solution + "\n")
        f.write("Nodes generated: " + str(info[1]) +
                "; Maximum nodes stored: " + str(info[2]) + "\n")
        f.write("Runtime: " + str(finaltime - inittime) + " seconds\n")
        f.write("\n")

        print("Finished breadth first search")

    elif algorithm == "dfs":
        inittime = time.time()
        info = search.depth_first_tree_search(sudoku)
        info[2] = info[2] + grid.count('.')
        finaltime = time.time()
        solution = sudoku.display(dict(info[0].state))
        f.write("DFS Algorithm Solution For " + grid + ":\n")
        f.write(solution + "\n")
        f.write("Nodes generated: " + str(info[1]) +
                "; Maximum nodes stored: " + str(info[2]) + "\n")
        f.write("Runtime: " + str(finaltime - inittime) + " seconds\n")
        f.write("\n")

        print("Finished depth first search")

    elif algorithm == "backtracking":
        inittime = time.time()
        result, num = csp.backtracking_search(sudoku, None)
        finaltime = time.time()
        solution = sudoku.display(dict(result))
        f.write("Backtracking Algorithm Solution For " + grid + ":\n")
        f.write(solution + "\n")
        f.write("Assignments made: " + str(num) + "\n")
        f.write("Runtime: " + str(finaltime - inittime) + " seconds\n")
        f.write("\n")

        print("Finished regular backtracking search")

    elif algorithm == "backtracking-ordered" or algorithm == "backtracking-noOrdering" or \
            algorithm == "backtracking-reverse":
        inittime = time.time()
        result, num = csp.backtracking_search(sudoku, algorithm)
        finaltime = time.time()
        solution = sudoku.display(dict(result))
        print(str(finaltime) + " " + str(inittime))
        f.write(algorithm + " Algorithm Solution For " + grid + ":\n")
        f.write(solution + "\n")
        f.write("Assignments made: " + str(num) + "\n")
        f.write("Runtime: " + str(finaltime - inittime) + " seconds\n")
        f.write("\n")
        f.close()

        print("Finished " + algorithm)
def pathExistsDFS(array, start, end, visited):
    for d in directions:
        i = start[0] + d[0]
        j = start[1] + d[1]
        next = [i, j]
        if i == end[0] and j == end[1]:
            return True
        if inBounds(array, next) and array[i][j] == '.' and not visited[i][j]:
            visited[i][j] = 1
            exists = pathExistsDFS(array, next, end, visited)
            if exists:
                return True
    return False


def inBounds(array, pos):
    #renvoie si on est toujours dans le state.array
    return 0 <= pos[0] and pos[0] < len(
        array) and 0 <= pos[1] and pos[1] < len(array[0])


#####################
# Launch the search #
#####################
tic = time.process_time()
problem = NumberLink(sys.argv[1])
solution = search.breadth_first_tree_search(problem)
for n in solution.path():
    print(n.state)
toc = time.process_time()
print("Le programme s'est exécuté en " + str(toc - tic) + " secondes.")
Beispiel #10
0
# Search methods

import search

ab = search.GPSProblem('U', 'C', search.romania)

print search.breadth_first_tree_search(ab)[0].path()
print search.breadth_first_tree_search(ab)[1]
#print search.depth_first_graph_search(ab).path()
#print search.iterative_deepening_search(ab).path()
#print search.depth_limited_search(ab).path()
print search.branch_and_bound_tree_search(ab)[0].path()
print search.branch_and_bound_tree_search(ab)[1]
print search.branch_and_bound_h_tree_search(ab)[0].path()
print search.branch_and_bound_h_tree_search(ab)[1]
#print search.astar_search(ab).path()

# Result:
# [<Node B>, <Node P>, <Node R>, <Node S>, <Node A>] : 101 + 97 + 80 + 140 = 418
# [<Node B>, <Node F>, <Node S>, <Node A>] : 211 + 99 + 140 = 450
        )

    def result(self, s, a):
        """Devuelve el estado resultante de aplicar una accion a un estado
           determinado."""
        # el estado resultante tiene la canoa en el lado opuesto, y con las
        # cantidades de misioneros y canibales actualizadas segun la cantidad
        # que viajaron en la canoa
        if s[2] == 0:
            return (s[0] - a[1][0], s[1] - a[1][1], 1)
        else:
            return (s[0] + a[1][0], s[1] + a[1][1], 0)


# creamos un problema a partir de nuestra formalizacion de ProblemaMisioneros
# como parametros le pasamos el estado inicial, y el estado meta que esperamos
p1 = ProblemaMisioneros((3, 3, 0), (0, 0, 1))

# le decimos a aima que resuelva nuestro problema con el metodo de busqueda en
# amplitud
r = breadth_first_tree_search(p1)
# esto nos devuelve el nodo meta del arbol. Podemos recorrer sus padres para
# tener todo el camino de acciones
camino_acciones = []
while r:
    if r.action:
        camino_acciones.append(r.action[0])
    r = r.parent

print " ".join(reversed(camino_acciones))
Beispiel #12
0
# Initial
initial = Point(50, 20)
goal = Point(10, 60)
matrix = init_matrix(initial, goal)
plot_result(matrix, initial, goal, 'Mapa do ambiente inicial')

# BFS
initial = Point(50, 20)
goal = Point(10, 60)

matrix = init_matrix(initial, goal)

search_problem = MatrixProblem(initial, goal, matrix)
start = time.time()

node = breadth_first_tree_search(search_problem)

end = time.time()
paint_solution(node, matrix)
print(''.join(['BFS search time: ', str(end - start)]))
plot_result(
    matrix, initial, goal,
    ''.join(['Busca em expansão (t = ',
             str(round(end - start, 4)), ' s)']))

# DFS
initial = Point(50, 20)
goal = Point(10, 60)
matrix = init_matrix(initial, goal)
search_problem = MatrixProblem(initial, goal, matrix)
start = time.time()
Beispiel #13
0
                node.state.board.targetPos) + node.state.board.getDistance(
                    robot_pos3,
                    node.state.board.targetPos) + node.state.board.getDistance(
                        robot_pos4, node.state.board.targetPos)

    def output(self, node: Node):
        actions = node.solution()
        print(len(actions))
        for action in actions:
            print(action[0] + " " + action[1])


if __name__ == "__main__":
    # Ler o ficheiro de input de sys.ar gv[1],
    board = parse_instance(sys.argv[1])
    # Usar uma técnica de procura para resolver a instância,
    problem = RicochetRobots(board)
    inst = InstrumentedProblem(problem)
    # Retirar a solução a partir do nó resultante,
    start = time.time()
    #solution_node = astar_search(inst)
    solution_node = breadth_first_tree_search(inst)
    end = time.time()
    print(end - start)
    #print(len(solution_node.path()))
    #print(len(solution_node.expand(problem)))
    #states = gerados, succs = expandidos, goal_tests = testados como solução
    print("expandidos: ", inst.states)
    print("gerados: ", inst.succs)
    # Imprimir para o standard output no formato indicado.
    #problem.output(solution_node)
Beispiel #14
0
        
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -



#______________________________________________________________________________
#

if __name__ == "__main__":

    sp = Sliding_puzzle(nr=3, nc=8, N=6)

    t0 = time.time()

    sol_ts = search.breadth_first_tree_search(sp)

    t1 = time.time()
    sp.print_solution(sol_ts)

    print ("Solver took ",t1-t0, ' seconds')


# + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 
#                              CODE CEMETARY
# + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 

#                if self.nr*self.nc<10:
#                    if t>0:
#                        print (t,end=' ')
#                    else:
Beispiel #15
0
import search

ab = search.GraphProblem('A', 'B', search.romania)
print search.breadth_first_tree_search(ab).solution()
Beispiel #16
0
def astar_tree_search(problem, h=None, display=False):
    h = memoize(h or problem.h, 'h')
    return best_first_tree_search(problem, lambda n: n.path_cost + h(n),
                                  display)


if __name__ == "__main__":

    input_file = sys.argv[1]
    algo = sys.argv[2]

    map_dict, heuristic, start, goal = parse(input_file)
    problem = MapProblem(start, goal, map_dict, heuristic)
    if algo == 'BFTS':
        goal_node = breadth_first_tree_search(problem)
    elif algo == 'DFTS':
        goal_node = depth_first_tree_search(problem)
    elif algo == 'DFGS':
        goal_node = depth_first_graph_search(problem)
    elif algo == 'BFGS':
        goal_node = breadth_first_graph_search(problem)
    elif algo == 'UCTS':
        goal_node = uniform_cost_tree_search(problem)
    elif algo == 'UCGS':
        goal_node = uniform_cost_search(problem)
    elif algo == 'GBFTS':
        goal_node = greedy_best_first_tree_search(problem)
    elif algo == 'GBFGS':
        goal_node = greedy_best_first_graph_search(problem, problem.h)
    elif algo == 'ASTS':
Beispiel #17
0
def romania_problem_test():
    problem = GraphProblem('Arad', 'Bucharest', romania_map)
    s = breadth_first_tree_search(problem)
    assert s.state == "Bucharest"