def init(): pacman = input("Posicion del pacman: ") pacman = validarPosicion(pacman) cereza = input("Posicion de la cereza: ") cereza = validarPosicion(cereza) NEWMAP = reemplazarPosicionesNoOcupadas(MAP, pacman, cereza) NEWMAP = [list(x) for x in NEWMAP.split("\n") if x] problem = PacmanProblem(NEWMAP) myviewer = WebViewer() # myviewer = ConsoleViewer() ans = True while ans: print(""" 1. Busqueda en anchura 2. Busqueda en profundidad 3. A* 4. Exit/Quit """) ans = raw_input("¿Cual opcion deseea ejecutar? ") if ans == "1": doBreadthFirst(NEWMAP, problem, myviewer) elif ans == "2": doDepthFirst(NEWMAP, problem, myviewer) elif ans == "3": doAStar(NEWMAP, problem, myviewer) elif ans == "4": ans = None exit() else: print("\n Opcion no valida.")
class HelloProblem(SearchProblem): def actions(self, state): if len(state) < len(GOAL): return list(' ABCDEFGHIJKLMNOPQRSTUVWXYZ') else: return [] def result(self, state, action): return state + action def is_goal(self, state): return state == GOAL def heuristic(self, state): # how far are we from the goal? wrong = sum( [1 if state[i] != GOAL[i] else 0 for i in range(len(state))]) missing = len(GOAL) - len(state) return wrong + missing my_viewer = WebViewer() problem = HelloProblem(initial_state='') # result = astar(problem) result = astar(problem, viewer=my_viewer) print(result.state) print(result.path())
def is_goal(self, state): return GOAL_STATE == state def actions(self, state): available_actions = [] print(ROOMS.get(state)) for room in ROOMS.get(state): available_actions.append((room)) return available_actions def result(self, state, action): room = action #convert tuples to list state_modifiable = state state_modifiable = (room) #convert list to tuples return state_modifiable def cost(self, state1,action, state2): return 1 problem = Labyrinth(INITIAL_STATE) result = breadth_first(problem, graph_search=True, viewer=WebViewer()) for element in result.path(): print(element) print(result)
def crossover(self, state1, state2): cut_point = randint(0, itemSize - 1) child = state1[:cut_point] + state2[cut_point:] return child def mutate(self, state): mutation = choice('01') mutation_point = randint(0, itemSize - 1) mutated = ''.join([ state[i] if i != mutation_point else mutation for i in range(len(state)) ]) return mutated problem = knapsack(initial_state='0101') result = genetic(problem, mutation_chance=0.1, viewer=WebViewer()) print(result.state) print(result.path()) ''' problem = knapsack(initial_state='0101') result = hill_climbing(problem, viewer=ConsoleViewer()) print(result.state) print(result.path()) ''' ''' problem = knapsack(initial_state='0101') result = hill_climbing_random_restarts(problem, viewer=ConsoleViewer()) print(result.state) print(result.path()) '''
posiciones_pendientes.append(robot) return sum([ manhattan(x, self.posicion_entrega) for x in posiciones_pendientes ]) def state_representation(self, state): pallets, robot, cargado, pendientes = state template = [[' '] * 5 for x in range(5)] for pallet, pos in enumerate(pallets): if pos is not None: fila, columna = pos template[fila][columna] = str(pallet + 1) x, y = self.posicion_entrega template[x][y] = 'E' r = 'R' if cargado: r = 'R' + str(cargado + 1) x, y = robot template[x][y] = r return '\n'.join([' | '.join(fila) for fila in template]) def manhattan(pos1, pos2): x1, y1 = pos1 x2, y2 = pos2 return abs(x2 - x1) + abs(y2 - y1) # Resolucion por A* result = astar(RobotProblem([8, 3, 9]), graph_search=True, viewer=WebViewer())
else: cols_diff = abs(queen - queen2) rows_diff = abs(queen_row - queen2_row) if cols_diff == rows_diff: attacks += 1 return -attacks def generate_random_state(self): state = [] for queen in range(8): queen_row = randint(0, 7) state.append(queen_row) return tuple(state) print("Hill climbing:") fixed_initial_state = (0, 0, 0, 0, 0, 0, 0, 0) problem = QueensProblem(fixed_initial_state) result = hill_climbing(problem, iterations_limit=9999, viewer=WebViewer()) print(result.state, problem.value(result.state)) print("Hill climbing random restarts:") problem = QueensProblem(None) result = hill_climbing_random_restarts(problem, restarts_limit=999, iterations_limit=9999) print(result.state, problem.value(result.state))
def cost(self, state1, action, state2): '''Returns the cost of performing an action. No useful on this problem, i but needed. ''' return 1 def heuristic(self, state): '''Returns an *estimation* of the distance from a state to the goal. We are using the manhattan distance. ''' rows = string_to_list(state) distance = 0 for number in '12345678e': row_n, col_n = find_location(rows, number) row_n_goal, col_n_goal = goal_positions[number] distance += abs(row_n - row_n_goal) + abs(col_n - col_n_goal) return distance #result = astar(EigthPuzzleProblem(INITIAL)) # if you want to use the visual debugger, use this instead: result = astar(EigthPuzzleProblem(INITIAL), viewer=WebViewer()) for action, state in result.path(): print('Move number', action) print(state)
] def esValido(self, estado): return (estado[0] >= estado[1]) or (estado[0] == 0) and \ (3 - estado[0]) >= (3 - estado[1]) or (estado[0] == 3) and \ (0 <= estado[0] <= 3) and \ (0 <= estado[1] <= 3) def is_goal(self, estado): return estado == (0, 0, 1) def result(self, estado, accion): if estado[2] == 0: return (estado[0] - accion[1][0], estado[1] - accion[1][1], 1) else: return (estado[0] + accion[1][0], estado[1] + accion[1][1], 0) def heuristic(self, estado): return (estado[0] + estado[1]) / 2 def value(self, estado): return 6 - estado[0] - estado[1] problema = Novios() visor = WebViewer() solucion = astar(problema, viewer=visor) #visor = ConsoleViewer #solucion = astar(problema, viewer=visor) print(solucion.path())
return 10 elif action[1]: return 5 return 2 def actions(self, state): movements = [ (True, False, False, True), (True, True, False, True), (True, False, True, True), (False, True, False, True), (False, True, True, True), (False, False, True, True), ] current = [x == state[3] for x in state[:3]] + [True] actions = [] for mov in movements: if not any([m and not c for m, c in zip(mov, current)]): actions.append(mov) return actions def result(self, state, action): return tuple([cross(x) if a else x for x, a in zip(state, action)]) result = uniform_cost(BridgeProblem(('I', 'I', 'I', 'I')), viewer=WebViewer(), graph_search=True)
available_actions.append(state[row_zero - 1][col_zero]) if row_zero < 2: available_actions.append(state[row_zero + 1][col_zero]) if col_zero > 0: available_actions.append(state[row_zero][col_zero - 1]) if col_zero < 2: available_actions.append(state[row_zero][col_zero + 1]) return available_actions def result(self, state, action): row_zero, col_zero = find(0, state) row_piece, col_piece = find(action, state) #convert tuples to list state_modifiable = list(list(row) for row in state) state_modifiable[row_zero][col_zero] = action state_modifiable[row_piece][col_piece] = 0 #convert list to tuples state_modifiable = tuple(tuple(row) for row in state_modifiable) return state_modifiable def cost(self, state1, action, state2): return 1 problem = EightPuzzle(INITIAL_STATE) result = breadth_first(problem, viewer=WebViewer())
state = str2list(state) row_e, col_e = find(state, 'e') row_n, col_n = find(state, action) state[row_e][col_e] = state[row_n][col_n] state[row_n][col_n] = 'e' return list2str(state) def heuristic(self, state): state = str2list(state) goal = str2list(GOAL) distance = 0 for number in '12345678': row_n, col_n = find(state, number) row_g, col_g = find(goal, number) distance += abs(row_n - row_g) + abs(col_n - col_g) return distance result = astar(OchoProblem(INITIAL), viewer=WebViewer()) #result = astar(OchoProblem(INITIAL)) print result.path() print len(result.path())
row_king - 1, col_king + 1) not in soldiers and ( row_king + 1, col_king + 1) not in soldiers: actions.append((row_king, col_king + 1)) if (row_king, col_king - 2) not in soldiers and ( row_king - 1) > 0 and (col_king + 1) < 7 and ( row_king - 1, col_king - 1) not in soldiers and ( row_king + 1, col_king - 1) not in soldiers: actions.append((row_king, col_king - 1)) return tuple(actions) def result(self, state, action): state = action return state def heuristic(self, state): distancias = [] for exit in exits: distancias.append(exit) return min([manhattan(x, state) for x in distancias]) def manhattan(pos1, pos2): x1, y1 = pos1 x2, y2 = pos2 return abs(x2 - x1) + abs(y2 - y1) my_viewer = BaseViewer() r = astar(HnefataflProblem(state), graph_search=True, viewer=WebViewer()) #print(my_viewer.stats)
def cost(self, state1, action, state2): 'El costo de la acción es la capacidad total del jarro origen' return action[0] + 1 def result(self, state, action): ''' Esta funcion le quita X litros a jarro origen y los pone en jarro_destino X puede ser los litros del jarro origen o lo que falte para llenar el jarro destino, lo que demande menos agua. ''' jarro_origen, jarro_destino = action litros_origen, litros_destino = state[jarro_origen], state[jarro_destino] a_trasvasar = min(litros_origen, self.capacidad(jarro_destino, litros_destino)) s = list(state) s[jarro_origen] -= a_trasvasar s[jarro_destino] += a_trasvasar return tuple(s) def heuristic(self, state): 'Una posible heuristica es la cantidad de jarros que no tienen agua' return len([x for x in state if x == 0]) # Resolucion por A* result = astar(JarrosProblem(4), graph_search=True, viewer=WebViewer())