############## return distance #------------------------------------------------------------------------------------------------------------------ # Program #------------------------------------------------------------------------------------------------------------------ # Initialize board initial_board = randomMovements(string_to_list('e-1-2\n3-4-5\n6-7-8'), 1000) initial_board = string_to_list('8-6-e-9\n7-1-2-10\n4-3-5-14\n12-11-13-15') initial_state = list_to_string(initial_board) # Create solver object result = astar(EightPuzzleProblem(initial_state), graph_search=True) # Print results for i, (action, state) in enumerate(result.path()): print() if action == None: print('Initial configuration') elif i == len(result.path()) - 1: print('Move: ' + str(i) + ' After moving', action, 'into the empty space. Goal achieved!') else: print('Move: ' + str(i) + ' After moving', action, 'into the empty space') print(state)
# Cost dictionary COSTS = { "up": cost_regular, "down": cost_regular, "left": cost_regular, "right": cost_regular, "up left": cost_regular, "up right": cost_regular, "down left": cost_regular, "down right": cost_regular, } # creating maze solver object problem = MazeSolver(MAP) # running solver result = astar(problem, graph_search=True) # extracting the path path = [x[1] for x in result.path()] # output file for the resulted path r = open("path-coord.txt", "w") # print result for debug purposes print() for y in range(len(MAP)): for x in range(len(MAP[y])): if (x, y) == problem.initial: print('o', end='') elif (x, y) == problem.goal: print('x', end='') elif (x, y) in path:
def doAStar(NEWMAP, problem, myviewer): result = astar(problem, graph_search=True, viewer=myviewer) path = [x[1] for x in result.path()] print("Ruta realizada A*:") print(result.path()) print(printMap(NEWMAP, problem, path))
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 = BaseViewer() problem = HelloProblem(initial_state='') # result = astar(problem) result = astar(problem,viewer=my_viewer) print(result.state) print(result.path())
x, y = p while (0 <= x < N) and (0 <= y < N): if (x, y) in pairs and (x, y) != original: tot += 1 x, y = x + delta_x, y + delta_y x, y = p while (0 <= x < N) and (0 <= y < N): if (x, y) in pairs and (x, y) != original: tot += 1 x, y = x - delta_x, y - delta_y return tot def print_board(self, s): N = self.N board = zip(range(N), s) for i in range(N): for j in range(N): if (i, j) in board: print 'Q', else: print '.', print '' # Run for the 8x8 case problem = NQueensSwap(N=8) result = astar(problem, graph_search=False) problem.print_board(result.state)
GOAL = [1, 3, 6, 8, 12] class TorchProblem(SearchProblem): def actions(self, state: Party): if (state.cost < 1): return [] else: if (state.direction): # A to B return [(x, y) for x in state.aSide for y in state.aSide] else: # B to A return [(x, y) for x in state.bSide for y in state.bSide] def result(self, state: Party, action: tuple): return state.modify(action) def is_goal(self, state: Party): temp = sorted(state.bSide) return temp == GOAL and state.cost >= 0 def heuristic(self, state: Party): return len(GOAL) - len(state.bSide) problem = TorchProblem(initial_state=Party([], GOAL.copy(), 30, True)) result = astar(problem) for x in result.path(): print((x[0], x[1].attr()))
state = string2list(state) cost = 0 for number, correct_position in GOAL_POSITIONS.items(): current_position = find_number(state, number) diff_x = abs(current_position[0] - correct_position[0]) diff_y = abs(current_position[1] - correct_position[1]) cost += diff_x + diff_y return cost def heuristic_MALA(self, state): cost = 0 for i in range(len(state)): if state[i] != '0' and state[i] != GOAL[i]: cost += 1 return cost visor = BaseViewer() # o WebViewer() o ConsoleViewer() result = astar(EightPuzzleProblem("7,2,4|5,0,6|8,3,1"), viewer=visor, graph_search=True) print result.state print result.path() print len(result.path()) print visor.stats
return [ (x, y) for x in range(4) for y in range(4) if (x, y) not in state and # asi no pone la carpa donde haya otra (x, y) not in arboles and # asi no pone la carpa donde haya un arbol tiene_vecinos((x, y), arboles) and # asi obliga a que la carpa se ponga vecina a algun arbol not tiene_vecinos((x, y), state) ] # asi obliga a que la carpa NO este vecina a las carpas ya puestas def result(self, state, action): # agrego la carpa a la lista de carpas ya puestas return state + (action, ) def cost(self, state1, action, state2): # poner una carpa siempre cuesta lo mismo return 1 def is_goal(self, state): # si puse 4 carpas, ya termine return len(state) == 4 def heuristic(self, state): # me faltan tantas acciones como carpas me falte ubicar para llegar a 4 return 4 - len(state) result = astar(ProblemaCarpas(tuple()), graph_search=True) print result.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())
rows = string_to_list( state) #La accion parameter contiene la ficha a mover row_e, col_e = find_location(rows, '0') row_n, col_n = find_location(rows, action) rows[row_e][col_e], rows[row_n][col_n] = rows[row_n][col_n], rows[ row_e][col_e] return list_to_string(rows) def is_goal(self, state): return state == GOAL #Devuelve true si el estado actual es el estado deseado def heuristic( self, state): #Regresa una estimacion de la distancia al estado deseado rows = string_to_list(state) distance = 1 for number in '123804765': 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(PuzzleProblem(INITIAL)) for action, state in result.path(): print('-----') print(state)
# 4.3 - esto tiene que tener un ojetivo class resolvedor(SearchProblem): def actions(self, estado): if len(estado) < len(objetivo): return list(caracteres) else: return [] def heuristic(self, estado): erradas = sum( [1 if estado[i] != objetivo[i] else 0 for i in range(len(estado))]) perdidas = len(objetivo) - len(estado) return erradas + perdidas def result(self, estado, accion): return estado + accion def is_goal(self, estado): return estado == objetivo # 5 - se instancia # se parte desde vacio # se crea un visualizador de solucion # se le dice que lo resuelva problema = resolvedor(initial_state="") visualizadorSolucion = ConsoleViewer() solucion = astar(problema, viewer=visualizadorSolucion) # Se procede a mostar la solucion: print(solucion.path())
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)
''' return 1 def heuristic(self, state): '''Returns an *estimation* of the distance from a state to the goal. We are using the manhattan distance. ''' # distance = 10 #l = list(state) #if l[0] == 'n': # distance -= 3 #if l[2] == 'n': # distance -= 3 #if l[6] == 'b': # distance -= 3 #if l[8] == 'b': # distance -= 3 # print ('state ', state) # print ('distance', distance) return 1 # result = astar(EigthPuzzleProblem(INITIAL)) # if you want to use the visual debugger, use this instead: # result = astar(EigthPuzzleProblem(INITIAL), viewer=WebViewer()) med = (('b', '.', 'b', '.', '.', '.', 'n', '.', 'n')) problem = Caballos(med) print(astar(problem))
robot, aentregar, enmano = state x, y = robot laentregar = list(aentregar) lenmano = list(enmano) if action[0] == 'Agarrar': laentregar.remove((action[1])) lenmano.append((action[1])) elif action[0] == 'Dejar': lenmano = [] else: x, y = action[1] return (x, y), tuple(laentregar), tuple(lenmano) def cost(self, state1, action, state2): return 1 def heuristic(self, state): robot, aentregar, enmano = state x, y = robot xx, yy = ENTREGA dif = (abs(x - xx), abs(y - yy)) return sum([len(aentregar), len(enmano), max(dif)]) problema = Problema(ESTADO) visor = BaseViewer() respuesta = astar(problema, graph_search=True, viewer=visor) for a in respuesta.path(): print a
def heuristic(self, state): # h2, manhattan distance total = 0 for number in range(1, 9): current_row, current_column = find_number(number, state) goal_row, goal_column = find_number(number, GOAL) distance = abs(current_row - goal_row) + abs(current_column - goal_column) total += distance return total viewer = WebViewer() # result = breadth_first(PuzzleProblem(INITIAL), graph_search=True) # result = depth_first(PuzzleProblem(INITIAL), graph_search=True) # result = uniform_cost(PuzzleProblem(INITIAL), graph_search=True, viewer=WebViewer()) # result = greedy(PuzzleProblem(INITIAL), graph_search=True, viewer=viewer) result = astar(PuzzleProblem(INITIAL), graph_search=True, viewer=viewer) print('Result state:') print(result.state) print('Result path:') for action, state in result.path(): print('Action:', action) print('State:', state) print('Solution at depth:', len(result.path())) print(viewer.stats)
statenuevo.remove((a, b - 1, 0)) statenuevo.append((a, b - 1, 1)) if (a + 1, b, 0) in state: statenuevo.remove((a + 1, b, 0)) statenuevo.append((a + 1, b, 1)) if (a, b + 1, 0) in state: statenuevo.remove((a, b + 1, 0)) statenuevo.append((a, b + 1, 1)) return tuple(statenuevo) def heuristic(self, state): cantidad = 0 for a in state: x, y, z = a if z == 0: cantidad = cantidad + 1 return cantidad / 5 def cost(self, state1, action, state2): return 1 problema = problem(((0, 0, 0), (0, 1, 0), (0, 2, 0), (1, 0, 0), (1, 1, 0), (1, 2, 0), (2, 0, 0), (2, 1, 0), (2, 2, 0))) visor = BaseViewer() resultado = astar(problema, graph_search=True, viewer=visor) print resultado for action, state in resultado.path(): print 'action', action print 'result', resultado
# apply all detected changes for change in changes_to_apply: if clothes[change] == 0: clothes[change] = 1 else: clothes[change] = 0 return circuit, previous_position, position, tuple(clothes) def heuristic(self, state): circuit, previous_position, position, clothes = state estimation = 0 # needs to do at least one movement if the position is not the goal one if position != 'E': estimation += 1 # needs to do at least one movement for each pair of things to change # (because it can change up to 2 things in one action) pending_changes = sum(1 for in_state, in_goal in zip(clothes, GOAL_CLOTHES) if in_state != in_goal) estimation += pending_changes / 2 return estimation result = astar(SantaProblem(INITIAL), graph_search=True) for action, state in result.path(): circuit, previous_position, position, clothes = state print(position, clothes)
''' rows = string_to_list(state) row_e, col_e = find_location(rows, 'e') row_n, col_n = find_location(rows, action) rows[row_e][col_e], rows[row_n][col_n] = rows[row_n][col_n], rows[row_e][col_e] return list_to_string(rows) def is_goal(self, state): '''Returns true if a state is the goal state.''' return state == GOAL 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)) for action, state in result.path(): print('Move number', action) print(state)
def find_path(self, start, end): problem = ShortestPathProblem(self.weights, start, end) result = astar(problem, graph_search=True) return result
# Final result that we want to achieve GOAL = '''1-2-3 4-5-6 7-8-e''' # Starting point INITIAL = '''1-e-2 6-3-4 7-5-8''' # Create a cache for the goal position of each piece goal_positions = {} rows_goal = string_to_list(GOAL) for number in '12345678e': goal_positions[number] = get_location(rows_goal, number) # Create the solver object result = astar(PuzzleSolver(INITIAL)) # Print the results for i, (action, state) in enumerate(result.path()): print() if action == None: print('Initial configuration') elif i == len(result.path()) - 1: print('After moving', action, 'into the empty space. Goal achieved!') else: print('After moving', action, 'into the empty space') print(state)
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())