Advertisement
Nikolovska

[ВИ] лаб 3.1 Подвижни препреки

Jun 11th, 2018
1,107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 20.83 KB | None | 0 0
  1. """Информирано пребарување (3)
  2.  
  3. Подвижни препреки
  4.  
  5. Предложете соодветна репрезентација и напишете ги потребните функции во Python за да се реши следниот проблем за кој
  6. една можна почетна состојба е прикажана на слика 1:
  7.  
  8. enter image description here
  9.  
  10. Слика 1
  11.  
  12. “Потребно е човечето безбедно да дојде до куќичката. Човечето може да се придвижува на кое било соседно поле
  13. хоризонтално или вертикално. Пречките 1, 2 и 3 се подвижни, при што пречката 1 се движи хоризонтално, пречката 2 се
  14. движи дијагонално, пречката 3 вертикално. Секоја од пречките се придвижува за едно поле во соодветниот правец и насока
  15. со секое придвижување на човечето. Притоа пречката 1 на почетокот се движи во лево, пречката 2 на почетокот се движи
  16. горе десно и пречката 3 на почетокот се движи надолу (пример за положбата на пречките после едно придвижување на
  17. човечето е прикажан на слика 2). Кога некоја пречка ќе дојде до крајот на таблата при што повеќе не може да се движи
  18. во насоката во која се движела, го менува движењето во спротивната насока. Доколку човечето и која било од пречките се
  19. најдат на исто поле - човечето ќе биде уништено.”
  20.  
  21. enter image description here
  22.  
  23. Слика 2
  24.  
  25. За сите тест примери изгледот и големината на таблата се исти како на примерот даден на сликите. За сите тест примери
  26. почетните положби, правец и насока на движење за препреките се исти. За секој тест пример почетната позиција на човечето
  27. се менува, а исто така се менува и позицијата на куќичката.
  28.  
  29. Во рамки на почетниот код даден за задачата се вчитуваат влезните аргументи за секој тест пример. Во променливите
  30. CoveceRedica и CoveceKolona ги имате редицата и колоната во која на почетокот се наоѓа човечето (ако таблата ја гледате
  31. како матрица). Во променливите KukaRedica и KukaKolona ги имате редицата и колоната во која се наоѓа куќичката
  32. (ако таблата ја гледате како матрица).
  33.  
  34. Движењата на човечето потребно е да ги именувате на следниот начин:
  35.  
  36. Desno - за придвижување на човечето за едно поле надесно
  37. Levo - за придвижување на човечето за едно поле налево
  38. Gore - за придвижување на човечето за едно поле нагоре
  39. Dolu - за придвижување на човечето за едно поле надолу
  40. Вашиот код треба да има само еден повик на функција за приказ на стандарден излез (print) со кој ќе ја вратите
  41. секвенцата на движења која човечето треба да ја направи за да може од својата почетна позиција да стигне до позицијата
  42. на куќичката. Треба да примените информирано пребарување. Искористете Менхетен растојание за имплементација на
  43. евристичката функција. """
  44.  
  45. import sys
  46. import bisect
  47.  
  48. infinity = float('inf')  # sistemski definirana vrednost za beskonecnost
  49.  
  50.  
  51. # ______________________________________________________________________________________________
  52. # Definiranje na pomosni strukturi za cuvanje na listata na generirani, no neprovereni jazli
  53.  
  54. class Queue:
  55.     """Queue is an abstract class/interface. There are three types:
  56.       Stack(): A Last In First Out Queue.
  57.       FIFOQueue(): A First In First Out Queue.
  58.       PriorityQueue(order, f): Queue in sorted order (default min-first).
  59.   Each type supports the following methods and functions:
  60.       q.append(item)  -- add an item to the queue
  61.       q.extend(items) -- equivalent to: for item in items: q.append(item)
  62.       q.pop()         -- return the top item from the queue
  63.       len(q)          -- number of items in q (also q.__len())
  64.       item in q       -- does q contain item?
  65.   Note that isinstance(Stack(), Queue) is false, because we implement stacks
  66.   as lists.  If Python ever gets interfaces, Queue will be an interface."""
  67.  
  68.     def __init__(self):
  69.         raise NotImplementedError
  70.  
  71.     def extend(self, items):
  72.         for item in items:
  73.             self.append(item)
  74.  
  75.  
  76. def Stack():
  77.     """A Last-In-First-Out Queue."""
  78.     return []
  79.  
  80.  
  81. class FIFOQueue(Queue):
  82.     """A First-In-First-Out Queue."""
  83.  
  84.     def __init__(self):
  85.         self.A = []
  86.         self.start = 0
  87.  
  88.     def append(self, item):
  89.         self.A.append(item)
  90.  
  91.     def __len__(self):
  92.         return len(self.A) - self.start
  93.  
  94.     def extend(self, items):
  95.         self.A.extend(items)
  96.  
  97.     def pop(self):
  98.         e = self.A[self.start]
  99.         self.start += 1
  100.         if self.start > 5 and self.start > len(self.A) / 2:
  101.             self.A = self.A[self.start:]
  102.             self.start = 0
  103.         return e
  104.  
  105.     def __contains__(self, item):
  106.         return item in self.A[self.start:]
  107.  
  108.  
  109. class PriorityQueue(Queue):
  110.     """A queue in which the minimum (or maximum) element (as determined by f and
  111.   order) is returned first. If order is min, the item with minimum f(x) is
  112.   returned first; if order is max, then it is the item with maximum f(x).
  113.   Also supports dict-like lookup. This structure will be most useful in informed searches"""
  114.  
  115.     def __init__(self, order=min, f=lambda x: x):
  116.         self.A = []
  117.         self.order = order
  118.         self.f = f
  119.  
  120.     def append(self, item):
  121.         bisect.insort(self.A, (self.f(item), item))
  122.  
  123.     def __len__(self):
  124.         return len(self.A)
  125.  
  126.     def pop(self):
  127.         if self.order == min:
  128.             return self.A.pop(0)[1]
  129.         else:
  130.             return self.A.pop()[1]
  131.  
  132.     def __contains__(self, item):
  133.         return any(item == pair[1] for pair in self.A)
  134.  
  135.     def __getitem__(self, key):
  136.         for _, item in self.A:
  137.             if item == key:
  138.                 return item
  139.  
  140.     def __delitem__(self, key):
  141.         for i, (value, item) in enumerate(self.A):
  142.             if item == key:
  143.                 self.A.pop(i)
  144.  
  145.  
  146. # ______________________________________________________________________________________________
  147. # Definiranje na klasa za strukturata na problemot koj ke go resavame so prebaruvanje
  148. # Klasata Problem e apstraktna klasa od koja pravime nasleduvanje za definiranje na osnovnite karakteristiki
  149. # na sekoj eden problem sto sakame da go resime
  150.  
  151.  
  152. class Problem:
  153.     """The abstract class for a formal problem.  You should subclass this and
  154.   implement the method successor, and possibly __init__, goal_test, and
  155.   path_cost. Then you will create instances of your subclass and solve them
  156.   with the various search functions."""
  157.  
  158.     def __init__(self, initial, goal=None):
  159.         """The constructor specifies the initial state, and possibly a goal
  160.       state, if there is a unique goal.  Your subclass's constructor can add
  161.       other arguments."""
  162.         self.initial = initial
  163.         self.goal = goal
  164.  
  165.     def successor(self, state):
  166.         """Given a state, return a dictionary of {action : state} pairs reachable
  167.       from this state. If there are many successors, consider an iterator
  168.       that yields the successors one at a time, rather than building them
  169.       all at once. Iterators will work fine within the framework. Yielding is not supported in Python 2.7"""
  170.         raise NotImplementedError
  171.  
  172.     def actions(self, state):
  173.         """Given a state, return a list of all actions possible from that state"""
  174.         raise NotImplementedError
  175.  
  176.     def result(self, state, action):
  177.         """Given a state and action, return the resulting state"""
  178.         raise NotImplementedError
  179.  
  180.     def goal_test(self, state):
  181.         """Return True if the state is a goal. The default method compares the
  182.       state to self.goal, as specified in the constructor. Implement this
  183.       method if checking against a single self.goal is not enough."""
  184.         return state == self.goal
  185.  
  186.     def path_cost(self, c, state1, action, state2):
  187.         """Return the cost of a solution path that arrives at state2 from
  188.       state1 via action, assuming cost c to get up to state1. If the problem
  189.       is such that the path doesn't matter, this function will only look at
  190.       state2.  If the path does matter, it will consider c and maybe state1
  191.       and action. The default method costs 1 for every step in the path."""
  192.         return c + 1
  193.  
  194.     def value(self):
  195.         """For optimization problems, each state has a value.  Hill-climbing
  196.       and related algorithms try to maximize this value."""
  197.         raise NotImplementedError
  198.  
  199.  
  200. # ______________________________________________________________________________
  201. # Definiranje na klasa za strukturata na jazel od prebaruvanje
  202. # Klasata Node ne se nasleduva
  203.  
  204. class Node:
  205.     """A node in a search tree. Contains a pointer to the parent (the node
  206.   that this is a successor of) and to the actual state for this node. Note
  207.   that if a state is arrived at by two paths, then there are two nodes with
  208.   the same state.  Also includes the action that got us to this state, and
  209.   the total path_cost (also known as g) to reach the node.  Other functions
  210.   may add an f and h value; see best_first_graph_search and astar_search for
  211.   an explanation of how the f and h values are handled. You will not need to
  212.   subclass this class."""
  213.  
  214.     def __init__(self, state, parent=None, action=None, path_cost=0):
  215.         "Create a search tree Node, derived from a parent by an action."
  216.         self.state = state
  217.         self.parent = parent
  218.         self.action = action
  219.         self.path_cost = path_cost
  220.         self.depth = 0
  221.         if parent:
  222.             self.depth = parent.depth + 1
  223.  
  224.     def __repr__(self):
  225.         return "<Node %s>" % (self.state,)
  226.  
  227.     def __lt__(self, node):
  228.         return self.state < node.state
  229.  
  230.     def expand(self, problem):
  231.         "List the nodes reachable in one step from this node."
  232.         return [self.child_node(problem, action)
  233.                 for action in problem.actions(self.state)]
  234.  
  235.     def child_node(self, problem, action):
  236.         "Return a child node from this node"
  237.         next = problem.result(self.state, action)
  238.         return Node(next, self, action,
  239.                     problem.path_cost(self.path_cost, self.state,
  240.                                       action, next))
  241.  
  242.     def solution(self):
  243.         "Return the sequence of actions to go from the root to this node."
  244.         return [node.action for node in self.path()[1:]]
  245.  
  246.     def solve(self):
  247.         "Return the sequence of states to go from the root to this node."
  248.         return [node.state for node in self.path()[0:]]
  249.  
  250.     def path(self):
  251.         "Return a list of nodes forming the path from the root to this node."
  252.         x, result = self, []
  253.         while x:
  254.             result.append(x)
  255.             x = x.parent
  256.         return list(reversed(result))
  257.  
  258.     # We want for a queue of nodes in breadth_first_search or
  259.     # astar_search to have no duplicated states, so we treat nodes
  260.     # with the same state as equal. [Problem: this may not be what you
  261.     # want in other contexts.]
  262.  
  263.     def __eq__(self, other):
  264.         return isinstance(other, Node) and self.state == other.state
  265.  
  266.     def __hash__(self):
  267.         return hash(self.state)
  268.  
  269.  
  270. # ________________________________________________________________________________________________________
  271. # Pomosna funkcija za informirani prebaruvanja
  272. # So pomos na ovaa funkcija gi keshirame rezultatite od funkcijata na evaluacija
  273.  
  274. def memoize(fn, slot=None):
  275.     """Memoize fn: make it remember the computed value for any argument list.
  276.   If slot is specified, store result in that slot of first argument.
  277.   If slot is false, store results in a dictionary."""
  278.     if slot:
  279.         def memoized_fn(obj, *args):
  280.             if hasattr(obj, slot):
  281.                 return getattr(obj, slot)
  282.             else:
  283.                 val = fn(obj, *args)
  284.                 setattr(obj, slot, val)
  285.                 return val
  286.     else:
  287.         def memoized_fn(*args):
  288.             if not memoized_fn.cache.has_key(args):
  289.                 memoized_fn.cache[args] = fn(*args)
  290.             return memoized_fn.cache[args]
  291.  
  292.         memoized_fn.cache = {}
  293.     return memoized_fn
  294.  
  295.  
  296. # ________________________________________________________________________________________________________
  297. # Informirano prebaruvanje vo ramki na graf
  298.  
  299. def best_first_graph_search(problem, f):
  300.     """Search the nodes with the lowest f scores first.
  301.   You specify the function f(node) that you want to minimize; for example,
  302.   if f is a heuristic estimate to the goal, then we have greedy best
  303.   first search; if f is node.depth then we have breadth-first search.
  304.   There is a subtlety: the line "f = memoize(f, 'f')" means that the f
  305.   values will be cached on the nodes as they are computed. So after doing
  306.   a best first search you can examine the f values of the path returned."""
  307.  
  308.     f = memoize(f, 'f')
  309.     node = Node(problem.initial)
  310.     if problem.goal_test(node.state):
  311.         return node
  312.     frontier = PriorityQueue(min, f)
  313.     frontier.append(node)
  314.     explored = set()
  315.     while frontier:
  316.         node = frontier.pop()
  317.         if problem.goal_test(node.state):
  318.             return node
  319.         explored.add(node.state)
  320.         for child in node.expand(problem):
  321.             if child.state not in explored and child not in frontier:
  322.                 frontier.append(child)
  323.             elif child in frontier:
  324.                 incumbent = frontier[child]
  325.                 if f(child) < f(incumbent):
  326.                     del frontier[incumbent]
  327.                     frontier.append(child)
  328.     return None
  329.  
  330.  
  331. def greedy_best_first_graph_search(problem, h=None):
  332.     "Greedy best-first search is accomplished by specifying f(n) = h(n)"
  333.     h = memoize(h or problem.h, 'h')
  334.     return best_first_graph_search(problem, h)
  335.  
  336.  
  337. def astar_search(problem, h=None):
  338.     "A* search is best-first graph search with f(n) = g(n)+h(n)."
  339.     h = memoize(h or problem.h, 'h')
  340.     return best_first_graph_search(problem, lambda n: n.path_cost + h(n))
  341.  
  342.  
  343. # ________________________________________________________________________________________________________
  344. # Dopolnitelni prebaruvanja
  345. # Recursive_best_first_search e implementiran
  346. # Kako zadaca za studentite da gi implementiraat SMA* i IDA*
  347.  
  348. def recursive_best_first_search(problem, h=None):
  349.     h = memoize(h or problem.h, 'h')
  350.  
  351.     def RBFS(problem, node, flimit):
  352.         if problem.goal_test(node.state):
  353.             return node, 0  # (The second value is immaterial)
  354.         successors = node.expand(problem)
  355.         if len(successors) == 0:
  356.             return None, infinity
  357.         for s in successors:
  358.             s.f = max(s.path_cost + h(s), node.f)
  359.         while True:
  360.             # Order by lowest f value
  361.             successors.sort(key=lambda x: x.f)
  362.             best = successors[0]
  363.             if best.f > flimit:
  364.                 return None, best.f
  365.             if len(successors) > 1:
  366.                 alternative = successors[1].f
  367.             else:
  368.                 alternative = infinity
  369.             result, best.f = RBFS(problem, best, min(flimit, alternative))
  370.             if result is not None:
  371.                 return result, best.f
  372.  
  373.     node = Node(problem.initial)
  374.     node.f = h(node)
  375.     result, bestf = RBFS(problem, node, infinity)
  376.     return result
  377.  
  378.  
  379. def update_p1(p1):
  380.     x, y, n = p1  # go proveruvame levoto kvadratce
  381.     if (y == 0 and n == -1) or (y == 4 and n == 1):
  382.         n *= -1
  383.     y_new = y + n
  384.     return x, y_new, n
  385.  
  386.  
  387. def update_p2(p2):
  388.     x, y, n = p2  # go proveruvame gornoto levo kvadratce
  389.     if (x == 5 and n == -1) or (x == 9 and n == 1):  
  390.         n *= -1
  391.     x_new = x + n
  392.     y_new = y - n
  393.     return x_new, y_new, n
  394.  
  395.  
  396. def update_p3(p3):
  397.     x, y, n = p3  # go proveruvame gornoto kvadratce
  398.     if (x == 5 and n == -1) or (x == 9 and n == 1):  
  399.         n *= -1
  400.     x_new = x + n
  401.     return x_new, y, n
  402.  
  403.  
  404. def isValid(x, y, p1, p2, p3):
  405.     # dali e nadvor od tabelata?
  406.     if x < 0 or y < 0 or x > 10 or y > 10:
  407.         return False
  408.     if y > 5 and x < 5:
  409.         return False
  410.  
  411.     # dali se sudira so nekoja od preprekite?
  412.     if (x == p1[0] and y == p1[1]) or (x == p1[0] and (y == p1[1] + 1)):
  413.         return False
  414.     if (x == p2[0] and y == p2[1]) or (x == p2[0] + 1 and y == p2[1]) or (x == p2[0] and y == p2[1] + 1) or (
  415.             x == p2[0] + 1 and y == p2[1] + 1):
  416.         return False
  417.     if (x == p3[0] and y == p3[1]) or (x == p3[0] + 1 and y == p3[1]):
  418.         return False
  419.  
  420.     return True
  421.  
  422.  
  423. class Istrazhucah(Problem):
  424.  
  425.     def __init__(self, initial=None, goal=None):
  426.         self.initial = initial
  427.         self.goal = goal
  428.  
  429.  
  430.     def successor(self, state):
  431.         successors = dict()
  432.         x, y = state[0]
  433.         p1 = state[1]
  434.         p2 = state[2]
  435.         p3 = state[3]
  436.         p1_new = update_p1(p1)
  437.         p2_new = update_p2(p2)
  438.         p3_new = update_p3(p3)
  439.  
  440.         # Gore
  441.         x_new = x - 1
  442.         if isValid(x_new, y, p1_new, p2_new, p3_new):
  443.             state_new = ((x_new, y), p1_new, p2_new, p3_new)
  444.             successors['Gore'] = state_new
  445.  
  446.         # Dolu
  447.         x_new = x + 1
  448.         if isValid(x_new, y, p1_new, p2_new, p3_new):
  449.             state_new = ((x_new, y), p1_new, p2_new, p3_new)
  450.             successors['Dolu'] = state_new
  451.  
  452.         # Levo
  453.         y_new = y - 1
  454.         if isValid(x, y_new, p1_new, p2_new, p3_new):
  455.             state_new = ((x, y_new), p1_new, p2_new, p3_new)
  456.             successors['Levo'] = state_new
  457.  
  458.         # Desno
  459.         y_new = y + 1
  460.         if isValid(x, y_new, p1_new, p2_new, p3_new):
  461.             state_new = ((x, y_new), p1_new, p2_new, p3_new)
  462.             successors['Desno'] = state_new
  463.  
  464.         return successors
  465.  
  466.     def actions(self, state):
  467.         return self.successor(state).keys()
  468.  
  469.  
  470.     def goal_test(self, state):
  471.         g = self.goal
  472.         x, y = state[0]
  473.         return x == g[0] and y == g[1]
  474.  
  475.     def path_cost(self, c, state1, action, state2):
  476.         """Return the cost of a solution path that arrives at state2 from
  477.        state1 via action, assuming cost c to get up to state1. If the problem
  478.        is such that the path doesn't matter, this function will only look at
  479.        state2.  If the path does matter, it will consider c and maybe state1
  480.        and action. The default method costs 1 for every step in the path."""
  481.         return c + 1
  482.  
  483.  
  484.     def result(self, state, action):
  485.         possible = self.successor(state)
  486.         return possible[action]
  487.  
  488.     def h(self, node):
  489.         """Funkcija koja ja presmetuva hevristikata,
  490.        t.e. Menheten rastojanieto pomegu nekoj tekoven jazel od prebaruvanjeto i celniot jazel"""
  491.         #x1, y1 = self.initial[0]
  492.         s = node.state
  493.         g = self.goal
  494.         return mhd(s[0],g)
  495.  
  496. def mhd(covece, cel):
  497.     x1, y1 = covece
  498.     x2, y2 = cel
  499.     return abs(x1 - x2) + abs(y1 - y2)
  500.  
  501.  
  502.  
  503. # Vcituvanje na vleznite argumenti za test primerite
  504.  
  505. CoveceRedica = int(input())
  506. CoveceKolona = int(input())
  507. KukaRedica = int(input())
  508. KukaKolona = int(input())
  509.  
  510. # Vasiot kod pisuvajte go pod ovoj komentar
  511.  
  512. Covece = (CoveceRedica, CoveceKolona)
  513. goal = (KukaRedica, KukaKolona)
  514. p1 = (2, 2, -1)
  515. p2 = (7, 2, -1)
  516. p3 = (7, 8, 1)
  517. initial = (Covece, p1, p2, p3)
  518.  
  519. #Coveche = Istrazhucah(((CoveceRedica, CoveceKolona), (2, 2, -1), (7, 2, -1), (7, 8, 1))(KukaRedica, KukaKolona))
  520. IstrazhucahInst = Istrazhucah(initial,goal)
  521.  
  522. answer = astar_search(IstrazhucahInst).solution()
  523. print(answer)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement