-
Notifications
You must be signed in to change notification settings - Fork 0
/
solutions.py
246 lines (216 loc) · 8.61 KB
/
solutions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
"""Reseni ukolu z notebooku.
"""
from collections import deque
from itertools import product
from math import inf
from search import is_goal, actions, move, log_search_step
def greedy_search(initial_state):
state = initial_state
plan = ''
while not is_goal(state):
available_actions = actions(state)
if not available_actions:
break # Failed to find a path.
# Choose the first available action (greedy choice).
action = available_actions[0]
state = move(state, action)
plan += action
# Return a complete or a partial path.
return plan
def all_plans_of_length(n):
return [''.join(plan) for plan in product('lfr', repeat=n)]
def is_correct(initial_state, plan):
state = initial_state
for action in plan:
state = move(state, action)
return is_goal(state)
def generate_and_test(initial_state):
for plan in all_plans_of_length(initial_state.n-1):
if is_correct(initial_state, plan):
return plan
# Nasledujici algoritmus neprochazi vrcholy v korektnim DFS poradi,
# protoze pridava do zasobniku vsechny nasledniky zkoumaneho stavu najednou
# a nikdy podruhe (pro zachovani liearni velikosti zasobniku).
# Pri hledani cesty k cilovemu stavu to nicemu nevadi, ale je
# dobre vedet, ze to neni presne DFS a pro nektere jine aplikace
# (napr. detekce orientovanych cyklu) by byl kod potreba upravit.
def dfs(initial_state):
stack = [initial_state]
plans = {initial_state: ''}
log_search_step(None, stack, plans)
while stack:
state = stack.pop()
if is_goal(state):
log_search_step(state, stack, plans)
return plans[state]
for action in reversed(actions(state)):
next_state = move(state, action)
if next_state not in plans: # jeste jsme ho nevideli
stack.append(next_state)
plans[next_state] = plans[state] + action
log_search_step(state, stack, plans)
# Tohle je "temer-korektni" iterativni implementace, ktera objevuje vzdy jedineho
# naslednika a stavy oznacuje za prozkoumane az po objeveni vsech nasledniku.
# Takto je prezentovan napr. v Algoritmech a datovych strukturach I.
# Pro optimalni casovou slozitost by se do zasobniku mela ukladat informace,
# ktereho naslednika budeme objevovat priste, cimz se vyhneme opakovanemu
# hledani prvniho neobjevenoho naslednika (to by vsak vyzadovalo upravit funkci
# pro vizualizaci algoritmu).
def dfs_correct(initial_state):
stack = [initial_state]
plans = {initial_state: ''}
log_search_step(None, stack, plans)
while stack:
state = stack.pop()
if is_goal(state):
log_search_step(state, stack, plans)
return plans[state]
explored = True
for action in actions(state):
next_state = move(state, action)
if next_state not in plans:
stack.append(state)
stack.append(next_state)
plans[next_state] = plans[state] + action
explored = False
break
log_search_step(state if explored else None, stack, plans)
# Varianta DFS s nasobnym ukladanim na zasobnik, ktera dosahuje korektniho
# poradi za cenu trochu komplikovanejsiho kodu a vetsi pametove slozitosti
# (zasobnik muze mit velikost poctu vsech hran).
def dfs_multistore(initial_state):
stack = [initial_state]
plans = {initial_state: ''}
explored = set()
log_search_step(None, stack, plans)
while stack:
state = stack.pop()
if is_goal(state):
log_search_step(state, stack, plans)
return plans[state]
# kontrola, zda jsme cil uz neprozkoumali
if state in explored:
continue
explored.add(state)
for action in reversed(actions(state)):
next_state = move(state, action)
# nasobne ukladani (neprozkoumane stavy se muzou na zasobniku
# objevit vickrat)
if next_state not in explored:
stack.append(next_state)
plans[next_state] = plans[state] + action
log_search_step(state, stack, plans)
def bfs(initial_state):
queue = deque([initial_state])
plans = {initial_state: ''}
log_search_step(None, queue, plans)
while queue:
state = queue.popleft()
# Cilovy test by u BFS slo provadet uz pri zarazovani do fronty.
if is_goal(state):
log_search_step(state, queue, plans)
return plans[state]
for action in actions(state):
next_state = move(state, action)
if next_state not in plans:
queue.append(next_state)
plans[next_state] = plans[state] + action
log_search_step(state, queue, plans)
ACTION_COSTS = {'l': 3, 'f': 2, 'r': 3}
def ucs(initial_state):
fringe = {initial_state}
costs = {initial_state: 0}
plans = {initial_state: ''}
log_search_step(None, fringe, plans, costs)
while fringe:
# Vybirame stav z okraje s nejnizsi cenou:
state = min(fringe, key=lambda s: costs[s])
fringe.remove(state)
if is_goal(state):
log_search_step(state, fringe, plans, costs)
return plans[state]
for action in actions(state):
next_state = move(state, action)
new_cost = costs[state] + ACTION_COSTS[action]
old_cost = costs.get(next_state, inf)
if new_cost < old_cost:
fringe.add(next_state)
costs[next_state] = new_cost
plans[next_state] = plans[state] + action
log_search_step(state, fringe, plans, costs)
def heuristic_distance(state):
# Cilovy radek ma hodnotu 0, radek pod nim 1, atd.
vertical_distance = state.spaceship.row
# Jaka by byla cena, kdyby raketka mohla letet porad rovne.
return vertical_distance * ACTION_COSTS['f']
def a_star(initial_state):
fringe = {initial_state}
costs = {initial_state: 0}
heuristic = {initial_state: heuristic_distance(initial_state)}
plans = {initial_state: ''}
log_search_step(None, fringe, plans, costs, heuristic)
while fringe:
state = min(fringe, key=lambda s: costs[s] + heuristic[s])
fringe.remove(state)
if is_goal(state):
log_search_step(state, fringe, plans, costs, heuristic)
return plans[state]
for action in actions(state):
next_state = move(state, action)
new_cost = costs[state] + ACTION_COSTS[action]
old_cost = costs.get(next_state, inf)
if new_cost < old_cost:
fringe.add(next_state)
costs[next_state] = new_cost
plans[next_state] = plans[state] + action
if next_state not in heuristic:
heuristic[next_state] = heuristic_distance(next_state)
log_search_step(state, fringe, plans, costs, heuristic)
# ----------------------------------------------------------------------------
# Obecne schema stromoveho prohledavani.
# Je parametrizovane typem okraje (Fringe), ktery
# popisuje strategii pro vyber stavu k prozkoumani.
def tree_search(initial_state, Fringe=set):
fringe = Fringe([initial_state])
plans = {initial_state: ''}
log_search_step(None, fringe, plans)
while fringe:
# Vyber jednoho stavu z okraje.
state = fringe.pop()
# Pokud je tento stav cilovy, muzeme prohledavani ukoncit.
if is_goal(state):
log_search_step(state, fringe, plans)
return plans[state]
# Pokud neni, expandujeme tento stav, tj. pridame na okraj
# vsechny jeho nasledniky.
for action in actions(state):
next_state = move(state, action)
plans[next_state] = plans[state] + action
fringe.add(next_state)
log_search_step(state, fringe, plans)
# Rekurzivni DFS pro stromy (nehlida zacykleni)
def recursive_dfs(state):
if is_goal(state):
return [state]
for action in actions(state):
next_state = move(state, action)
path = recursive_dfs(next_state)
if path:
return [state] + path
return None # no path found
# Rekurzivni DFS pro grafy (hlida zacykleni)
def recursive_graph_dfs(start_state):
explored = set()
def dfs(state):
explored.add(state)
if is_goal(state):
return [state]
for action in actions(state):
next_state = move(state, action)
if next_state in explored:
continue
path = dfs(next_state)
if path:
return [state] + path
return None # no path found
return dfs(start_state)