Advertisement
Nikolovska

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

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