def test_bfs_4steps(): global goal_state print "Testing BFS in 4 steps..." hp_0 = HuarongPass(initial_state) hp_24 = HuarongPass(step_24_state) hp_41 = HuarongPass(step_41_state) hp_59 = HuarongPass(step_59_state) goal_state = step_24_state acts_0_24 = search.breadth_first_search(hp_0).solution() goal_state = step_41_state acts_24_41 = search.breadth_first_search(hp_24).solution() goal_state = step_59_state acts_41_59 = search.breadth_first_search(hp_41).solution() goal_state = None acts_59_81 = search.breadth_first_search(hp_59).solution() print len(acts_0_24), acts_0_24 print len(acts_24_41), acts_24_41 print len(acts_41_59), acts_41_59 print len(acts_59_81), acts_59_81 acts = acts_0_24 + acts_24_41 + acts_41_59 + acts_59_81 print "Total steps: ", len(acts) audit_state(hp_0.state_given(initial_state, acts)) print "BFS test complete. (4 step)"
def huarong_pass_search(search_name): goal_actions = [] hp = HuarongPass() if search_name == 'BFS': # print "Breadth first search...good choice. ", time.asctime() goal_actions = search.breadth_first_search(hp).solution() elif search_name == 'DFS': # print "Depth first search...really?", time.asctime() goal_actions = search.depth_first_graph_search(hp).solution() elif search_name == 'IDS': # print "Iterative deepening search...great choice!", time.asctime() goal_actions = search.iterative_deepening_search(hp).solution() elif search_name == 'BID': # print "Bidirectional search...not required...using BFS instead..." goal_actions = huarong_pass_search('BFS') elif search_name == 'DLS': # print "Depth limited search...", time.asctime() goal_actions = search.depth_limited_search(hp, DEPTH_LIMIT).solution() else: print "Invalid search_name given. Exiting..." return goal_actions
def test_breadth_first_search_four_step(): # plan of length 4 task = dummy_task.get_simple_search_space_2() solution = breadth_first_search(task) print(solution) assert solution != None assert len(solution) == 4
def test_breadth_first_search_at_goal(): # plan of length 0, start == goal task = dummy_task.get_search_space_at_goal() solution = breadth_first_search(task) print(solution) assert solution != None assert len(solution) == 0
def test_bfs(): print "Testing BFS..." # test_bfs_7steps() # test_bfs_4steps() hp_0 = HuarongPass(initial_state) hp_57 = HuarongPass(step_57_state) goal_state = None acts_57_81 = search.breadth_first_search(hp_57).solution() print len(acts_57_81), acts_57_81 acts = acts_57_81 print "Total steps: ", len(acts) audit_state(hp_0.state_given(step_57_state, acts)) print "BFS test complete."
def length_of_shortest_cycle(incidents, vert1, vert2): """Returns the length of the shortest cycle in a graph with given INCIDENTS through the edge VERT1 --> VERT2. Assumes this edge is not contained in incidents.""" problem = GraphSearchProblem(vert1, vert2, graph_path_goal_test, incidents) x = breadth_first_search(problem) return x[3]
def main(): game = solitaire([['O', '_', '_', 'O', '_'], ['O', '_', 'O', '_', 'O'], ['_', 'O', '_', 'O', '_'], ['O', '_', 'O', '_', '_'], ['_', 'O', '_', '_', '_']]) p = InstrumentedProblem(game) resultBreadthFirstSearch = breadth_first_search(p) print(resultBreadthFirstSearch.solution()) print(resultBreadthFirstSearch.path()[0].state.board)
def main(): print("MAIN") prob1 = Calculator() prob2 = Calculator((2, 6, 0), (2, 6, 15)) prob3 = Calculator((3, 7, 11), (3, 7, 100)) # Resolviendo el problema 1: print("Problema 1: (2, 3, 0) -> 13") print("Solución del Problema 1 mediante búsqueda primero en anchura") meta1 = breadth_first_search(prob1) if meta1: despliega_solucion(meta1) else: print("Falla: no se encontró una solución") # Resolviendo el problema 2: print("Problema 2: (2, 6, 0) -> 15") print("Solución del Problema 2 mediante búsqueda primero en anchura") meta2 = breadth_first_search(prob2) if meta2: despliega_solucion(meta2) else: print("Falla: no se encontró una solución") # Resolviendo el problema 3: print("Problema 3: (3, 7, 11) -> 100") print("Solución del Problema 3 mediante búsqueda primero en anchura") meta3 = breadth_first_search(prob3) if meta3: despliega_solucion(meta3) else: print("Falla: no se encontró una solución") # Resolviendo el problema 3: print("\nProblema 3: (3, 7, 11) -> 100") print("Solución del Problema 3 mediante A*") meta4 = astar_search(prob3) if meta3: despliega_solucion(meta4) else: print("Falla: no se encontró una solución")
def bfs_tests(breadth_first_search): romania = pickle.load(open('romania_graph.pickle', 'rb')) bfs_paths = pickle.load( open('solution_files/romania_bfs_test_paths.pickle', 'rb')) for key, value in bfs_paths.items(): start, goal = key right_path, right_closed = value romania.reset_search() path = breadth_first_search(romania, start, goal) closed = list(romania.get_explored_nodes()) path_is_valid = is_path_correct(romania, start, goal, path) max_nodes_explored = max(int(len(right_closed) * 1.2), len(right_closed) + 3) node_exploration_valid = len(closed) <= max_nodes_explored path_is_correct = True if path and right_path: path_is_correct = len(path) <= len(right_path) if (path and not right_path) or (not path and right_path): path_is_correct = False if not (path_is_valid and node_exploration_valid and path_is_correct): print( 'Breadth first search fails benchmarks searching from %s to %s: ' % (start, goal)) if not path_is_valid: print('Path %s does not go from %s to %s' % (str(path), str(start), str(goal))) if not node_exploration_valid: print( 'Nodes explored should be a valid frontier, and be no more than %d in number' % (max_nodes_explored)) if not path_is_correct: print('Path %s is longer than an optimal path %s' % (str(path), str(right_path))) return print('BFS tests passed.')
def main(): # Runs the Family police thief problem, will provide a path to move all family members to the right side without # leaving the mom alone with the male children, the dad alone with the female children, and the thief with any of # the family members without the police officer print('Family Cop Thief Problem: ') print( ' Tuples are in this format --> [<Node (mom, dad, leftFemaleKid, leftMaleKid,rightFemaleKid, rightMaleKid,police, thief, boatSide)>]') goalState = (1, 1, 0, 0, 2, 2, 1, 1, 1) problem = FRP(goalState) goal = breadth_first_search(problem) # print("\nPath = ",goal.path(),"\n\nPath cost = ",goal.path_cost) print(" Steps = " + str(goal.path()), "\n Cost = " + str(goal.path_cost)) print()
def main(): """Default function to be called when the program executes.""" # Create an instance of the Search class with arguments from argparse searcher = Search(start, stop, args.grid) # Return the correct searching algorithm for a given specification if args.alg == 'bfs': search = aima.breadth_first_search(searcher) elif args.alg == 'ucs': search = aima.uniform_cost_search(searcher) else: search = aima.astar_search(searcher) return search.path()
def test_bfs_7steps(): global goal_state print "Testing BFS in 7 steps..." hp_0 = HuarongPass() hp_0.set_initial_state(initial_state) hp_24 = HuarongPass(step_24_state) hp_30 = HuarongPass(step_30_state) hp_41 = HuarongPass(step_41_state) hp_48 = HuarongPass(step_48_state) hp_59 = HuarongPass(step_59_state) hp_72 = HuarongPass(step_72_state) hp_81 = HuarongPass(step_81_state) goal_state = step_24_state acts_0_24 = search.breadth_first_search(hp_0).solution() goal_state = step_30_state acts_24_30 = search.breadth_first_search(hp_24).solution() goal_state = step_41_state acts_30_41 = search.breadth_first_search(hp_30).solution() goal_state = step_48_state acts_41_48 = search.breadth_first_search(hp_41).solution() goal_state = step_59_state acts_48_59 = search.breadth_first_search(hp_48).solution() goal_state = step_72_state acts_59_72 = search.breadth_first_search(hp_59).solution() goal_state = None acts_72_81 = search.breadth_first_search(hp_72).solution() print len(acts_0_24), acts_0_24 print len(acts_24_30), acts_24_30 print len(acts_30_41), acts_30_41 print len(acts_41_48), acts_41_48 print len(acts_48_59), acts_48_59 print len(acts_59_72), acts_59_72 print len(acts_72_81), acts_72_81 acts = acts_0_24 + acts_24_30 + acts_30_41 + acts_41_48 + acts_48_59 + acts_59_72 + acts_72_81 print "Total steps: ", len(acts) audit_state(hp_0.state_given(initial_state, acts)) print "BFS test complete. (7 step)"
def main(): #Runs the Water Jug problem, will provide a solution to fill the three jugs # to a 2,2,3 configuration without overfilling a jug and only by pouring # until the pouring jug is empty or the recieving jug is full print('Water Jug Problem: ') print( ' Tuples are in this format --> [<Node (Seven-liter, Four-liter, Three-liter)>]' ) goalState = (2, 2, 3) problem = WJP(goalState) goal = breadth_first_search(problem) print("\nPath = ", goal.path(), "\n\nPath cost = ", goal.path_cost) #print(" Steps = " + str(goal.path()), "\n Cost = " + str(goal.path_cost)) print()
def get_all_states(dim=3): """ In order to get all possible states for an npuzzle, you can simply pass any valid n-puzzle state as the initial state, and an invalid n-puzzle state as the goal; the """ # goal state should be a tuple of the the first dim*dim positive intgers goal_state = tuple(range(1, dim*dim + 1)) invalid_state = invalid_init_state(dim) # invalid_state is easy to produce. npp = NPuzzleProblem(invalid_state, goal_state) allstates = search.breadth_first_search(npp) return allstates
def populate(self, projected_task, vars_maps, actions_maps): from itertools import product from search import breadth_first_search from model.generic.planning.task import State var_map, inv_var_map = vars_maps action_map, inv_action_map = actions_maps domains = [x.domain for x in projected_task.task.state_vars] value_index = 0 self.unsolvable_count = 0 self.num_non_zero_entries = 0 self.max_value = 0 for valuation in apply(product, map(tuple, domains)): value_index += 1 # indexed with the original vars entry_index = tuple([(inv_var_map[x], v) for x, v in enumerate(valuation)]) s0 = State(projected_task.task, [(x, v) for x, v in enumerate(valuation)]) projected_task.set_initial_state(s0) projected_task.initial_state.check_valid() if not projected_task.initial_state.valid: self.table[entry_index] = Entry(float('inf'), None) self.unsolvable_count += 1 continue plan = breadth_first_search(projected_task, True) if plan is None: self.table[entry_index] = Entry(float('inf'), None) self.unsolvable_count += 1 continue first_action_in_plan = None if len(plan) > 0: self.num_non_zero_entries += 1 first_action_in_plan = inv_action_map[plan[0].index] self.table[entry_index] = Entry(len(plan), first_action_in_plan) self.max_value = max(self.max_value, len(plan)) logging.info('# of infinite entries in pattern: {0}'.format( self.unsolvable_count)) logging.info('# of entries with a value greater than 0: {0}'.format( self.num_non_zero_entries)) logging.info('Maximum value in pattern: {0}'.format(self.max_value))
def bfs_tests(breadth_first_search): romania = pickle.load(open('romania_graph.pickle', 'rb')) bfs_paths = pickle.load(open('solution_files/romania_bfs_test_paths.pickle', 'rb' )) for key, value in bfs_paths.items(): start, goal = key right_path, right_closed = value romania.reset_search() path = breadth_first_search(romania, start, goal) closed = list(romania.get_explored_nodes()) path_is_valid = is_path_correct(romania, start, goal, path) max_nodes_explored = max(int(len(right_closed) * 1.2), len(right_closed) + 3) node_exploration_valid = len(closed) <= max_nodes_explored path_is_correct = True if path and right_path: path_is_correct = len(path) <= len(right_path) if (path and not right_path) or (not path and right_path): path_is_correct = False if not (path_is_valid and node_exploration_valid and path_is_correct): print('Breadth first search fails benchmarks searching from %s to %s: '%(start, goal)) if not path_is_valid: print('Path %s does not go from %s to %s'%(str(path),str(start), str(goal))) if not node_exploration_valid: print('Nodes explored should be a valid frontier, and be no more than %d in number'%(max_nodes_explored)) if not path_is_correct: print('Path %s is longer than an optimal path %s'%(str(path),str(right_path))) return print('BFS tests passed.')
def main(): """Run simple test using BFS to solve random puzzle.""" puzzle = create_random_eight_puzzle(25) print('A random puzzle:') print(puzzle) problem = EightPuzzleSearchProblem(puzzle) path = search.breadth_first_search(problem) print(('BFS found a path of %d moves: %s' % (len(path), str(path)))) curr = puzzle i = 1 for a in path: curr = curr.result(a) print(('After %d move%s: %s' % (i, ("", "s")[i > 1], a))) print(curr) input("Press return for the next state...") # wait for key stroke i += 1
def test_breath_first_search(self): print( "Starting breath first search test", "If it cannot finish within 30s, " "please kill the job and review your code") print("---------------------------------------------") puzzle = EightPuzzleState([3, 0, 5, 6, 2, 4, 7, 8, 1]) problem = PuzzleSearchProblem(puzzle) path, step = search.breadth_first_search(problem) print("Test BFS on: \n") print(puzzle) self.print_result("BFS", step, problem.get_costs(path), path) curr = puzzle for a in path: curr = curr.next_state(a) self.assertTrue(curr.is_goal(), "The final state is not goal test") print("=============================================")
def test_breath_first_search(self): print("Starting breath first search test") print("---------------------------------------------") with Timer(30, error_message= "Breath First Search cannot find the solution within 30s"): puzzle = EightPuzzleState([3, 0, 5, 6, 2, 4, 7, 8, 1]) problem = PuzzleSearchProblem(puzzle) path, step = search.breadth_first_search(problem) print("Test BFS on: \n") print(puzzle) self.print_result("BFS", step, problem.get_costs(path), path) curr = puzzle for a in path: curr = curr.next_state(a) self.assertTrue(curr.is_goal(), "The final state is not goal test") print("=============================================")
def BuscaLargura(self): table = self.get_table() print(table) initial_state = StateNode(Game8(table), None, None, 0, 0) start = int(round(time.time() * 1000)) path = breadth_first_search(initial_state) end = int(round(time.time() * 1000)) for state in path: self.depth_label['text'] = 'Profundidade: ' + str(state.depth) b = state.game.get_b_position() state.game.table[b[0]][b[1]] = '' self.set_table(state.game.table) state.game.show_table() time.sleep(1) self.generated_nodes_label['text'] = 'Nós gerados: ' + str( s.generated_nodes) self.execution_time['text'] = 'Tempo de execução (ms): ' + str(end - start)
def find_path_to_closest_dot(self, game_state): """ Returns a path (a list of actions) to the closest dot, starting from game_state. """ # Here are some useful elements of the start_state start_position = game_state.get_pacman_position() food = game_state.get_food() walls = game_state.get_walls() problem = AnyFoodSearchProblem(game_state) "*** YOUR CODE HERE ***" """ The Breadth First Search algorithm is guaranteed to find a path to the closest dot and it is optimal in this scenario because the cost of each action is one """ return search.breadth_first_search(problem)
def run(algorithm, grid, start, stop): """Verify that the start and stop locations are valid then run the indicated search algorithms and return the final node. If no algorithm is indicated it will default to A_star search :param algorithm: The search algorithm to use :param grid: grid to find a path through :param start: starting location :param stop: goal location :return: The path taken """ # Verify start and stop position are valid if not valid_position(grid, start): try: if grid[start] == 0: print(start, 'Is not a valid start position, it is in an obstacle.') except IndexError: print( start, 'Is not a valid start position. Start position must be within the grid: ', grid.shape) exit() if not valid_position(grid, stop): try: if grid[stop] == 0: print(stop, 'Is not a valid stop position, it is an obstacle.') except IndexError: print( stop, 'Is not a valid stop position. Stop position must be within the range of the grid shape:', grid.shape) exit() my_problem = PathingProblem(start, stop, grid) # Creating instance of PathingProblem if algorithm == 'breadth_first_search' or algorithm == 'b': return breadth_first_search(my_problem) elif algorithm == 'depth_first_graph_search' or algorithm == 'd': return depth_first_graph_search(my_problem) else: # Defaults to a_star search return astar_search(my_problem)
from board import buildGrid from board import toggleCell from board import buildGrid from board import parseBoard from cleanUpPuzzle import CleanUpPuzzle from search import breadth_first_search from search import uniform_cost_search from display import displayProblemSolution import time BOARD_SIZE = 6 HARD_BOARD = [ '0|1|0|0|0|1', '0|0|1|0|0|0', '0|0|0|1|0|1', '0|1|0|0|1|0', '0|0|1|0|0|0', '0|0|0|0|0|0' ] start_time = time.time() easy_goal = breadth_first_search( CleanUpPuzzle( '\n'.join(HARD_BOARD), buildGrid(size = BOARD_SIZE) ) ) print(easy_goal) displayProblemSolution(easy_goal, 'breadth_first_search', time.time() - start_time)
from trees import Node from search import (depth_first_search, breadth_first_search, recursion_tree_traverse) # Setup Tree root = Node(0) root.left = Node(1) root.right = Node(2) root.left.left = Node(3) root.left.right = Node(4) root.right.left = Node(5) root.right.right = Node(6) print('Depth First Search') depth_first_search(root) print('=' * 25) print('Breadth First Search') breadth_first_search(root) print('Recursion Tree Traversal') recursion_tree_traverse(root)
print() print('=' * 50) print('=' * 50) print("EIGHT-PUZZLE PROBLEM") print('=' * 50) print('=' * 50) ep = EightPuzzleProblem([[3, 1, 2], [7, 5, 0], [4, 6, 8]]) print() print('-' * 50) print("Running BREADTH-FIRST-TREE-SEARCH") print('-' * 50) bfts = breadth_first_search(ep, search_type=uninformed_tree_search) print("Solution", bfts.solution()) print() print('-' * 50) print("Running UNIFORM-COST-TREE-SEARCH") print('-' * 50) ucts = uniform_cost_search(ep, search_type=best_first_tree_search) print("Solution", ucts.solution()) print() print('-' * 50) print(
result.append((x, y + 1)) return result def push(self, x, y): adjacent_points = self.get_adjacent_nodes(x, y) for point in adjacent_points: if point in self.points: self.points.remove(point) else: self.points.append(point) def print_solution(result): print("Initial board is: {}".format(result.path()[0].state)) print("The sequence is:") for action in result.solution(): print("Push tile {}".format(action)) print("Resultant board is: {}".format(result.state)) initial_state = PuzzleState( points=[(0, 1), (1, 0), (9, 10), (10, 9), (5, 4), (5, 6), (4, 5), (6, 5)]) goal = PuzzleState(points=[]) puzzle = CleanUpPuzzle(initial_state, goal=goal) result = breadth_first_search(puzzle) if result: print_solution(result)
moves: number of random moves to apply Creates a random eight puzzle by applying a series of 'moves' random moves to a solved puzzle. """ puzzle = EightPuzzleState([0, 1, 2, 3, 4, 5, 6, 7, 8]) for i in range(moves): # Execute a random legal move puzzle = puzzle.result(random.sample(puzzle.legal_moves(), 1)[0]) return puzzle if __name__ == '__main__': puzzle = create_random_eight_puzzle(25) print('A random puzzle:') print(puzzle) problem = EightPuzzleSearchProblem(puzzle) path = search.breadth_first_search(problem) print(('BFS found a path of %d moves: %s' % (len(path), str(path)))) curr = puzzle i = 1 for a in path: curr = curr.result(a) print(('After %d move%s: %s' % (i, ("", "s")[i > 1], a))) print(curr) input("Press return for the next state...") # wait for key stroke i += 1
def test_breadth_first_search_no_solution(): # plan with no solution task = dummy_task.get_search_space_no_solution() solution = breadth_first_search(task) print(solution) assert solution == None
''' Created on Oct 2, 2016 @author: farida ''' from search import romania_map, GraphProblem, breadth_first_tree_search,\ depth_first_graph_search, iterative_deepening_search,\ recursive_best_first_search, breadth_first_search, uniform_cost_search,\ depth_limited_search print("Romania Locations:") print("==================") print(romania_map.locations) print("Romania Map:") print("=============") print(romania_map.dict) romania_problem = GraphProblem('Arad', 'Bucharest', romania_map) print("Search Algorithms Results:") print("==========================") print(breadth_first_search(romania_problem).solution()) #print(breadth_first_search(romania_problem).path_cost) print(uniform_cost_search(romania_problem).solution()) #print(uniform_cost_search(romania_problem).path_cost) print(depth_first_graph_search(romania_problem).solution()) print(depth_first_graph_search(romania_problem).path_cost)
''' from search import romania_map, GraphProblem, breadth_first_tree_search,\ depth_first_graph_search, iterative_deepening_search,\ recursive_best_first_search, breadth_first_search, uniform_cost_search,\ depth_limited_search print("Romania Locations:") print("==================") print(romania_map.locations) print("Romania Map:") print("=============") print(romania_map.dict) romania_problem = GraphProblem('Arad', 'Bucharest', romania_map) print("Search Algorithms Results:") print("==========================") print(breadth_first_search(romania_problem).solution()) #print(breadth_first_search(romania_problem).path_cost) print(uniform_cost_search(romania_problem).solution()) #print(uniform_cost_search(romania_problem).path_cost) print(depth_first_graph_search(romania_problem).solution()) print(depth_first_graph_search(romania_problem).path_cost)
if grid[i][j] == u'air': grid[i][j] = 'a' elif grid[i][j] == u'diamond_block': grid[i][j] = 'd' elif grid[i][j] == u'emerald_block': grid[i][j] = 'E' elif grid[i][j] == u'redstone_block': grid[i][j] = 'R' else: grid[i][j] = '?' pretty_print_grid(grid) problem = MazeProblem(grid) if search_alg == 'bfs': plan = breadth_first_search(problem) elif search_alg == 'gs': plan = greedy_search(problem) if plan: for action in plan: print 'action: {0}'.format(action) command = commands[action] agent_host.sendCommand(command) time.sleep(0.5) world_state = agent_host.getWorldState() if world_state.is_mission_running or len( world_state.rewards ) == 0 or world_state.rewards[-1].getValue() < 100.0: print 'Mission failed: did not reach goal state.' break
def solve(self, start_status): start_node = self.nodes.index(start_status) shortest_path = breadth_first_search(start_node, self.node_edges, self.is_solved) return [self.nodes[node] for node in shortest_path]
print print '=' * 50 print '=' * 50 print "EIGHT-PUZZLE PROBLEM" print '=' * 50 print '=' * 50 ep = EightPuzzleProblem([[3, 1, 2], [7, 5, 0], [4, 6, 8]]) print print '-' * 50 print "Running BREADTH-FIRST-TREE-SEARCH" print '-' * 50 bfts = breadth_first_search(ep, search_type=uninformed_tree_search) print "Solution", bfts.solution() print print '-' * 50 print "Running UNIFORM-COST-TREE-SEARCH" print '-' * 50 ucts = uniform_cost_search(ep, search_type=best_first_tree_search) print "Solution", ucts.solution() print print '-' * 50 print "Running GREEDY-BEST-FIRST-TREE-SEARCH USING # MISPLACED TILES HEURISTIC"
return 2 elif node.state == 'F': return 10 elif node.state == 'G': return 0 elif node.state == 'S': return 8 travel_problem = TravelProblem('S', 'G', city_map) print() print('-' * 50) print("Q2: BREADTH-FIRST-TREE-SEARCH") print('-' * 50) bfts = breadth_first_search(travel_problem, search_type=uninformed_graph_search) print("Solution", bfts.solution()) print() print('-' * 50) print("Q3: UNIFORM-COST-GRAPH-SEARCH") print('-' * 50) ucs = uniform_cost_search(travel_problem, search_type=best_first_graph_search) print("Solution", ucs.solution()) print() print('-' * 50)
""" python run_A_Star.py heuristicNo size steps """ arg = sys.argv heuristic = int(arg[1]) p = puzzle(None, True, "inputState.txt", False, None) startTime = time.time() if heuristic == 0 : solution = breadth_first_search(p) elif heuristic == 1 : solution = astar_search(p, lambda x : h1(x, p.goal)) elif heuristic == 2 : solution = astar_search(p, lambda x : h2(x, p.goal)) elif heuristic == 3 : solution = astar_search(p, lambda x : h3(x, p.goal)) elif heuristic == 4 : solution = astar_search(p, lambda x : h4(x, p.goal)) solution = solution.solution() if solution != None: print "Actions made : ", len(solution) print "Time elapsed : %.3f" % (time.time() - startTime)
#------------------------------------------------------------------- # EJEMPLOS DE USO # Problema 1: (3,3,1) -> (0,0,0) para 3 misioneros y 3 caníbales prob1 = MisionerosYCanibales() # Problema 2: (2,2,0) -> (0,0,1) para 3 misioneros y 3 caníbales prob2 = MisionerosYCanibales((2, 2, 0), (0, 0, 1)) # Problema 3: (4,4,1) -> (2,2,0) para 4 misioneros y 4 caníbales prob3 = MisionerosYCanibales((4, 4, 1), (2, 2, 0), 4) # Problema 4: (6,5,1) -> (6,0,0) para 6 misioneros y 6 caníbales prob4 = MisionerosYCanibales((6, 5, 1), (6, 0, 0), 6) # Resolviendo el problema 1: print("Solución del Problema 1 mediante búsqueda primero en anchura") meta1 = breadth_first_search(prob1) if meta1: despliega_solucion(meta1) else: print("Falla: no se encontró una solución") # Resolviendo el problema 2: print("Solución del Problema 2 mediante búsqueda primero en anchura") meta2 = breadth_first_search(prob2) if meta2: despliega_solucion(meta2) else: print("Falla: no se encontró una solución") # Resolviendo el problema 3: print("Solución del Problema 3 mediante búsqueda primero en anchura")
if __name__ == '__main__': # TODO This should be unchanged in the final program you hand in, but it might be useful to make a copy, # comment out one copy, and modify the other to get things to run more quickly while you're debugging depths = (1, 2, 4, 8, 16) trials = 100 path_lengths = {} state_counts = {} for depth in depths: print('Gathering data for depth ' + str(depth) + '...') path_lengths[depth] = {'BFS': [], 'IDS': [], 'A*-mis': [], 'A*-Man': []} state_counts[depth] = {'BFS': [], 'IDS': [], 'A*-mis': [], 'A*-Man': []} for trial in range(trials): puzzle = EightPuzzle(depth) p = search.InstrumentedProblem(puzzle) path_lengths[depth]['BFS'].append(len(search.breadth_first_search(p).path())) state_counts[depth]['BFS'].append(p.states) p = search.InstrumentedProblem(puzzle) path_lengths[depth]['IDS'].append(len(search.iterative_deepening_search(p).path())) state_counts[depth]['IDS'].append(p.states) p = search.InstrumentedProblem(puzzle) path_lengths[depth]['A*-mis'].append(len(search.astar_search(p, misplaced).path())) state_counts[depth]['A*-mis'].append(p.states) p = search.InstrumentedProblem(puzzle) path_lengths[depth]['A*-Man'].append(len(search.astar_search(p, manhattan).path())) state_counts[depth]['A*-Man'].append(p.states) print('Path lengths:') print('{:>5} {:>8} {:>8} {:>8} {:>8}'.format('Depth', 'BFS', 'IDS', 'A*-mis', 'A*-Man')) for depth in depths: print('{:>5} {:>8} {:>8} {:>8} {:>8}' \ .format(depth,
'BFS': [], 'IDS': [], 'A*-mis': [], 'A*-Man': [] } state_counts[depth] = { 'BFS': [], 'IDS': [], 'A*-mis': [], 'A*-Man': [] } for trial in range(trials): puzzle = EightPuzzle(depth) p = search.InstrumentedProblem(puzzle) path_lengths[depth]['BFS'].append( len(search.breadth_first_search(p).path())) state_counts[depth]['BFS'].append(p.states) p = search.InstrumentedProblem(puzzle) path_lengths[depth]['IDS'].append( len(search.iterative_deepening_search(p).path())) state_counts[depth]['IDS'].append(p.states) p = search.InstrumentedProblem(puzzle) path_lengths[depth]['A*-mis'].append( len(search.astar_search(p, misplaced).path())) state_counts[depth]['A*-mis'].append(p.states) p = search.InstrumentedProblem(puzzle) path_lengths[depth]['A*-Man'].append( len(search.astar_search(p, manhattan).path())) state_counts[depth]['A*-Man'].append(p.states) print('Path lengths:') print('{:>5} {:>8} {:>8} {:>8} {:>8}'.format('Depth', 'BFS', 'IDS',