diff --git a/BorisovMI/lab_1/docs/data/structures.py b/BorisovMI/lab_1/docs/data/structures.py new file mode 100644 index 0000000..ea514c1 --- /dev/null +++ b/BorisovMI/lab_1/docs/data/structures.py @@ -0,0 +1,477 @@ +import time +import random +import csv +import os +import matplotlib.pyplot as plt +import numpy as np +import sys +sys.setrecursionlimit(20000) +# Связный список + +def ll_insert(head, name, phone): + + new_node = {'name': name, 'phone': phone, 'next': None} + + if head is None: + return new_node + + if head['name'] == name: + head['phone'] = phone + return head + + current = head + while current['next'] is not None: + if current['next']['name'] == name: + current['next']['phone'] = phone + return head + current = current['next'] + + current['next'] = new_node + return head + +def ll_find(head, name): + + current = head + while current is not None: + if current['name'] == name: + return current['phone'] + current = current['next'] + return None + +def ll_delete(head, name): + + if head is None: + return None + + if head['name'] == name: + return head['next'] + + current = head + while current['next'] is not None: + if current['next']['name'] == name: + current['next'] = current['next']['next'] + return head + current = current['next'] + + return head + +def ll_list_all(head): + + records = [] + current = head + while current is not None: + records.append((current['name'], current['phone'])) + current = current['next'] + records.sort(key=lambda x: x[0]) + return records + +# Хэш функции + +def hash_function(name, table_size): + return sum(ord(c) for c in name) % table_size + + +def ht_create(size=1000): + return [None] * size + + +def ht_insert(buckets, name, phone): + size = len(buckets) + index = hash_function(name, size) + buckets[index] = ll_insert(buckets[index], name, phone) + + +def ht_find(buckets, name): + size = len(buckets) + index = hash_function(name, size) + return ll_find(buckets[index], name) + + +def ht_delete(buckets, name): + size = len(buckets) + index = hash_function(name, size) + buckets[index] = ll_delete(buckets[index], name) + + +def ht_list_all(buckets): + records = [] + for bucket in buckets: + current = bucket + while current is not None: + records.append((current['name'], current['phone'])) + current = current['next'] + records.sort(key=lambda x: x[0]) + return records + +# Функции для дерева поиска + +def bst_insert(root, name, phone): + + if root is None: + return {'name': name, 'phone': phone, 'left': None, 'right': None} + + if name < root['name']: + root['left'] = bst_insert(root['left'], name, phone) + elif name > root['name']: + root['right'] = bst_insert(root['right'], name, phone) + else: + root['phone'] = phone + + return root + + +def bst_find(root, name): + + current = root + while current is not None: + if name == current['name']: + return current['phone'] + elif name < current['name']: + current = current['left'] + else: + current = current['right'] + return None + + +def bst_find_min(node): + + current = node + while current['left'] is not None: + current = current['left'] + return current + + +def bst_delete(root, name): + + if root is None: + return None + + if name < root['name']: + root['left'] = bst_delete(root['left'], name) + elif name > root['name']: + root['right'] = bst_delete(root['right'], name) + else: + if root['left'] is None: + return root['right'] + elif root['right'] is None: + return root['left'] + + min_node = bst_find_min(root['right']) + root['name'] = min_node['name'] + root['phone'] = min_node['phone'] + root['right'] = bst_delete(root['right'], min_node['name']) + + return root + + +def bst_list_all(root): + + records = [] + + def inorder_traversal(node): + if node is not None: + inorder_traversal(node['left']) + records.append((node['name'], node['phone'])) + inorder_traversal(node['right']) + + inorder_traversal(root) + return records + + # Генерация тестовых данных + +def generate_records(count=10000): + + records = [] + for i in range(count): + name = f"User_{i:05d}" + phone = f"+7-{random.randint(100,999)}-{random.randint(100,999)}-{random.randint(1000,9999)}" + records.append((name, phone)) + + shuffled = records.copy() + random.shuffle(shuffled) + sorted_records = sorted(records, key=lambda x: x[0]) + + return shuffled, sorted_records + + + +# Замер времени + +def measure_insertion(structure_name, records): + + times = [] + filled_structure = None + + for run in range(5): + if structure_name == "linked_list": + structure = None + elif structure_name == "hash_table": + structure = ht_create(1000) + elif structure_name == "bst": + structure = None + + start = time.perf_counter() + + for name, phone in records: + if structure_name == "linked_list": + structure = ll_insert(structure, name, phone) + elif structure_name == "hash_table": + ht_insert(structure, name, phone) + elif structure_name == "bst": + structure = bst_insert(structure, name, phone) + + end = time.perf_counter() + times.append(end - start) + + if run == 4: + filled_structure = structure + + return times, filled_structure + +def measure_search(structure_name, structure, search_names): + + times = [] + + for run in range(5): + start = time.perf_counter() + + for name in search_names: + if structure_name == "linked_list": + ll_find(structure, name) + elif structure_name == "hash_table": + ht_find(structure, name) + elif structure_name == "bst": + bst_find(structure, name) + + end = time.perf_counter() + times.append(end - start) + + return times + +def measure_deletion(structure_name, original_structure, delete_names): + + times = [] + + for run in range(5): + if structure_name == "linked_list": + all_records = ll_list_all(original_structure) + test_structure = None + for name, phone in all_records: + test_structure = ll_insert(test_structure, name, phone) + + elif structure_name == "hash_table": + all_records = ht_list_all(original_structure) + test_structure = ht_create(1000) + for name, phone in all_records: + ht_insert(test_structure, name, phone) + + elif structure_name == "bst": + all_records = bst_list_all(original_structure) + test_structure = None + for name, phone in all_records: + test_structure = bst_insert(test_structure, name, phone) + + start = time.perf_counter() + + for name in delete_names: + if structure_name == "linked_list": + test_structure = ll_delete(test_structure, name) + elif structure_name == "hash_table": + ht_delete(test_structure, name) + elif structure_name == "bst": + test_structure = bst_delete(test_structure, name) + + end = time.perf_counter() + times.append(end - start) + + return times + +# Основная часть + +def run_experiment(): + + current_dir = os.path.dirname(__name__) + docs_dir = os.path.dirname(current_dir) + csv_file = os.path.join(docs_dir, "experiment_results.csv") + + print("=" * 70) + print("ЭКСПЕРИМЕНТАЛЬНОЕ СРАВНЕНИЕ СТРУКТУР ДАННЫХ") + print("Телефонный справочник - 10000 записей") + print("=" * 70) + print(f"\nРезультаты будут сохранены в: {csv_file}") + + print("\n1. Генерация тестовых данных...") + shuffled_records, sorted_records = generate_records(10000) + print(f" Сгенерировано 10000 записей") + + existing_names = [shuffled_records[i][0] for i in random.sample(range(10000), 100)] + nonexisting_names = [f"NotExist_{i}" for i in range(10)] + search_names = existing_names + nonexisting_names + delete_names = [shuffled_records[i][0] for i in random.sample(range(10000), 50)] + + results = [["Структура", "Режим", "Операция", + "Замер1(с)", "Замер2(с)", "Замер3(с)", "Замер4(с)", "Замер5(с)", + "Среднее(с)"]] + + for mode_name, records in [("случайный", shuffled_records), + ("отсортированный", sorted_records)]: + + print(f"\n2. Тестирование режима: {mode_name}") + print("-" * 50) + + for struct_name in ["linked_list", "hash_table", "bst"]: + print(f"\n {struct_name.upper()}:") + + print(" Вставка 10000 записей...") + insert_times, filled_struct = measure_insertion(struct_name, records) + avg_insert = sum(insert_times) / 5 + print(f" Время: {avg_insert:.4f} сек (среднее)") + + print(" Поиск 110 записей...") + search_times = measure_search(struct_name, filled_struct, search_names) + avg_search = sum(search_times) / 5 + print(f" Время: {avg_search:.4f} сек (среднее)") + + print(" Удаление 50 записей...") + delete_times = measure_deletion(struct_name, filled_struct, delete_names) + avg_delete = sum(delete_times) / 5 + print(f" Время: {avg_delete:.4f} сек (среднее)") + + results.append([struct_name, mode_name, "вставка"] + insert_times + [avg_insert]) + results.append([struct_name, mode_name, "поиск"] + search_times + [avg_search]) + results.append([struct_name, mode_name, "удаление"] + delete_times + [avg_delete]) + + print("\n3. Сохранение результатов...") + with open(csv_file, "w", newline="", encoding="utf-8") as f: + writer = csv.writer(f) + writer.writerows(results) + print(f" Результаты сохранены в: {csv_file}") + + print("\n" + "=" * 70) + print("СВОДНАЯ ТАБЛИЦА РЕЗУЛЬТАТОВ") + print("=" * 70) + print(f"{'Структура':<15} {'Режим':<12} {'Операция':<10} {'Среднее время (сек)':<20}") + print("-" * 70) + + for row in results[1:]: + struct, mode, op, t1, t2, t3, t4, t5, avg = row + print(f"{struct:<15} {mode:<12} {op:<10} {avg:<20.6f}") + + return results, docs_dir + +# Графики + +def create_graphs(results, docs_dir): + + print("\n4. Построение графиков...") + + data = {} + for row in results[1:]: + struct = row[0] + mode = row[1] + op = row[2] + avg = row[8] + + if struct not in data: + data[struct] = {} + if mode not in data[struct]: + data[struct][mode] = {} + data[struct][mode][op] = avg + + + struct_labels = { + 'linked_list': 'LinkedList', + 'hash_table': 'HashTable', + 'bst': 'BST' + } + + + colors = { + 'linked_list': '#3498db', + 'hash_table': '#2ecc71', + 'bst': '#e74c3c' + } + + + fig, axes = plt.subplots(1, 3, figsize=(15, 6)) + fig.suptitle('Сравнение производительности структур данных', fontsize=16, fontweight='bold') + + operations = ['вставка', 'поиск', 'удаление'] + operation_titles = ['Вставка\n(10000 записей)', 'Поиск\n(110 запросов)', 'Удаление\n(50 записей)'] + modes = ['случайный', 'отсортированный'] + mode_labels = ['Случайный', 'Отсортированный'] + + for idx, (op, op_title) in enumerate(zip(operations, operation_titles)): + ax = axes[idx] + + # Позиции для групп столбцов + x = np.arange(len(modes)) # [0, 1] + width = 0.25 # ширина одного столбца + multiplier = 0 + + for struct in ['linked_list', 'hash_table', 'bst']: + values = [data[struct][mode][op] for mode in modes] + offset = width * multiplier + bars = ax.bar(x + offset, values, width, + label=struct_labels[struct], + color=colors[struct], + edgecolor='black', linewidth=0.5) + + + for bar, val in zip(bars, values): + if val < 0.01: + ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + val*0.05, + f'{val:.5f}', ha='center', va='bottom', fontsize=8, rotation=0) + else: + ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + val*0.02, + f'{val:.4f}', ha='center', va='bottom', fontsize=8, rotation=0) + + multiplier += 1 + + + ax.set_title(op_title, fontsize=12, fontweight='bold') + ax.set_ylabel('Время (секунды)', fontsize=10) + ax.set_xlabel('Режим данных', fontsize=10) + ax.set_xticks(x + width) + ax.set_xticklabels(mode_labels) + ax.legend(loc='upper left', fontsize=8) + ax.grid(True, alpha=0.3, axis='y') + + + all_values = [data[s][m][op] for s in ['linked_list', 'hash_table', 'bst'] for m in modes] + if max(all_values) / min(all_values) > 100: + ax.set_yscale('log') + ax.set_ylabel('Время (секунды) - логарифмическая шкала', fontsize=9) + + plt.tight_layout() + graph_path = os.path.join(docs_dir, "performance_graphs.png") + plt.savefig(graph_path, dpi=150, bbox_inches='tight') + plt.close() + print(f" Графики сохранены в: {graph_path}") + + return graph_path + + + +if __name__ == "__main__": + + results, docs_dir = run_experiment() + + + try: + graph_file = create_graphs(results, docs_dir) + + print("\n" + "=" * 70) + print("ЭКСПЕРИМЕНТ ЗАВЕРШЕН УСПЕШНО!") + print("=" * 70) + print("\nСОЗДАННЫЕ ФАЙЛЫ:") + print(f" Данные: {os.path.join(docs_dir, 'experiment_results.csv')}") + print(f" Графики: {graph_file}") + + except Exception as e: + print(f"\nОшибка при построении графиков: {e}") + print(" Убедитесь, что установлен matplotlib: pip install matplotlib") + print("\n" + "=" * 70) + print("ЭКСПЕРИМЕНТ ЗАВЕРШЕН (без графиков)") + print("=" * 70) + print(f"\nCSV файл сохранен: {os.path.join(docs_dir, 'experiment_results.csv')}") \ No newline at end of file diff --git a/BorisovMI/lab_1/docs/experiment_results.csv b/BorisovMI/lab_1/docs/experiment_results.csv new file mode 100644 index 0000000..b3a472b --- /dev/null +++ b/BorisovMI/lab_1/docs/experiment_results.csv @@ -0,0 +1,19 @@ +Структура,Режим,Операция,Замер1(с),Замер2(с),Замер3(с),Замер4(с),Замер5(с),Среднее(с) +linked_list,случайный,вставка,11.072574299992993,12.38099840003997,12.155311000009533,12.81002289999742,13.201067199988756,12.323994760005736 +linked_list,случайный,поиск,0.1209169999929145,0.13400630000978708,0.1302103999769315,0.12179599999217317,0.13267739996081218,0.12792141998652368 +linked_list,случайный,удаление,0.05278969998471439,0.05019940005149692,0.05289009999250993,0.0488043999648653,0.061356800026260316,0.05320808000396937 +hash_table,случайный,вставка,0.694432099990081,0.7192347000236623,0.7134853000170551,0.6891152000171132,0.6973775000078604,0.7027289600111544 +hash_table,случайный,поиск,0.006584499962627888,0.004749000014271587,0.004359900020062923,0.006477299961261451,0.006112299975939095,0.005656599986832589 +hash_table,случайный,удаление,0.004070399969350547,0.004140400036703795,0.003542299964465201,0.0032371999695897102,0.0030583000043407083,0.0036097199888899924 +bst,случайный,вставка,0.08137199998600408,0.08989329996984452,0.08159760001581162,0.07841239997651428,0.1001471999916248,0.08628449998795987 +bst,случайный,поиск,0.0006561999907717109,0.00043180002830922604,0.00042429997120052576,0.0004227000172249973,0.00043509999522939324,0.0004740200005471706 +bst,случайный,удаление,0.19723930000327528,0.166880399978254,0.147482400003355,0.18100009998306632,0.16498840000713244,0.1715181199950166 +linked_list,отсортированный,вставка,12.294058899977244,11.597062399960123,11.59195000003092,11.623520500026643,11.401553199975751,11.701628999994137 +linked_list,отсортированный,поиск,0.10066379996715114,0.0991929000010714,0.09696789999725297,0.09909789997618645,0.09873830003198236,0.09893215999472886 +linked_list,отсортированный,удаление,0.05669830000260845,0.048193000024184585,0.05076910002389923,0.04920080001465976,0.05905079998774454,0.05278240001061931 +hash_table,отсортированный,вставка,0.5518350999918766,0.5407364999991842,0.5291212999727577,0.5373308000271209,0.529426000022795,0.5376899400027468 +hash_table,отсортированный,поиск,0.005108800018206239,0.004848999960813671,0.004103399987798184,0.0038874000310897827,0.005848900007549673,0.00475950000109151 +hash_table,отсортированный,удаление,0.0037329999613575637,0.003185699984896928,0.0028516000020317733,0.0030229000258259475,0.0037879000301472843,0.003316220000851899 +bst,отсортированный,вставка,32.23637629998848,33.77348939998774,33.518200399994384,33.78866110002855,33.55791890004184,33.3749292200082 +bst,отсортированный,поиск,0.1479294000309892,0.1305704999831505,0.13548930000979453,0.1314462999580428,0.130273999995552,0.1351418999955058 +bst,отсортированный,удаление,0.1574716999894008,0.16461069998331368,0.15460990002611652,0.15385339997010306,0.15677610004786402,0.15746436000335962 diff --git a/BorisovMI/lab_1/docs/performance_graphs.png b/BorisovMI/lab_1/docs/performance_graphs.png new file mode 100644 index 0000000..8cfee3f Binary files /dev/null and b/BorisovMI/lab_1/docs/performance_graphs.png differ diff --git a/BorisovMI/lab_1/docs/report.md b/BorisovMI/lab_1/docs/report.md new file mode 100644 index 0000000..ee21dec --- /dev/null +++ b/BorisovMI/lab_1/docs/report.md @@ -0,0 +1,73 @@ +# Отчёт: Задание 1 — Структуры данных + +## Цель работы + +Реализовать три структуры данных «с нуля» в процедурной парадигме (без классов), применить их для хранения записей телефонного справочника и экспериментально сравнить производительность основных операций. + +## Описание реализованных структур + +Связный список +- Узел: {'name': str, 'phone': str, 'next': dict или None} +- Операции проходят путём последовательного обхода элементов +- Подходит для небольших объёмов данных + +Хеш-таблица +- Массив корзин фиксированного размера (1000) +- Хеш-функция: сумма кодов символов имени по модулю размера +- Разрешение коллизий: метод цепочек (связные списки) + +Двоичное дерево поиска +- Узел: {'name': str, 'phone': str, 'left': dict, 'right': dict} +- Левое поддерево содержит меньшие значения +- Правое поддерево содержит большие значения + + +## Условия эксперимента + +Общее количество записей - 10 000 +Количество замеров для каждой операции - 5 +Размер хеш-таблицы - 1000 корзин +Количество поисковых запросов - 110 (100 существующих + 10 несуществующих) +Количество удаляемых записей - 50 +Режимы вставки данных - Случайный / Отсортированный +Инструмент замера времени - time.perf_counter() + + +## Результаты + +### Таблица средних времён (секунды) + +| Структура | Режим | Вставка (с) | Поиск 110 (с) | Удаление 50 (с) | +|---|---|---|---|---| +| LinkedList | случайный | 12.32399 | 0.1279214 | 0.053208 | +| LinkedList | сортированный | 11.701628 | 0.0989321 | 0.052782 | +| HashTable | случайный | 0.7027289 | 0.0056565 | 0.0036097 | +| HashTable | сортированный | 0.5376899 | 0.0047595 | 0.003316 | +| BST | случайный | 0.08628449 | 0.000474 | 0.1715181 | +| BST | сортированный | 33.374929 | 0.1351418 | 0.1574643 | + +### Графики + +![Сравнение по операциям](performance_graphs.png) + +## Анализ результатов + +### Связный список + +Вставка в список занимает ~2.5 секунды на 10 000 записей, потому что каждая вставка уже существующего имени требует прохода по всему списку O(n). При случайных уникальных именах вставка идёт в начало O(1), но поиск всегда линейный. + +### Хеш-таблица + +Хеш-таблица показала примерно одинаковые результаты при случайном и отсортированном порядке: + +Это объясняется природой хеширования: порядок вставки не влияет на распределение по бакетам. Ключ всегда попадает в предсказуемый бакет за O(1). + +### BST + +деградирует на отсортированных данных + +Причина:*при вставке отсортированных данных BST вырождается в односвязный список — каждый новый элемент больше предыдущего и уходит всегда в правое поддерево. Высота дерева становится O(n) вместо O(log n). Поиск и удаление тоже деградируют до O(n). + +## Вывод + +HashTable — лучший выбор для телефонного справочника при частых вставках и поисках. BST лучше HashTable только если нужен отсортированный вывод без дополнительной сортировки — но при условии случайного порядка вставки или использования самобалансирующегося дерева (AVL, Red-Black). diff --git a/BorisovMI/lab_2/docs/data/maze.py b/BorisovMI/lab_2/docs/data/maze.py new file mode 100644 index 0000000..46ad99e --- /dev/null +++ b/BorisovMI/lab_2/docs/data/maze.py @@ -0,0 +1,725 @@ +from abc import ABC, abstractclassmethod +from collections import deque +import heapq +import time +import os +import time +import csv +import random +class Cell: + def __init__(self, x, y): + self.x = x + self.y = y + self.isWall = False + self.isStart = False + self.isExit = False + + + def __eq__(self, other): + if other is None: + return False + return self.x == other.x and self.y == other.y + def __lt__(self, other): + + if other is None: + return False + return (self.x, self.y) < (other.x, other.y) + def __hash__(self): + + return hash((self.x, self.y)) + + def __repr__(self): + return f"Cell({self.x}, {self.y})" + def isPassable(self): + return not self.isWall + +class Maze: + def __init__(self, width, height): + self.width = width + self.height = height + self.grid = [[Cell(x, y) for y in range(height)] for x in range(width)] + self.start = None + self.exit = None + + def getCell(self, x, y): + if 0 <= x < self.width and 0 <= y < self.height: + return self.grid[x][y] + return None + + def getNeighbors(self, cell): + neighbors = [] + directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] + for dx, dy in directions: + neighbor = self.getCell(cell.x + dx, cell.y + dy) + if neighbor and neighbor.isPassable(): + neighbors.append(neighbor) + return neighbors + + def setStart(self, x, y): + cell = self.getCell(x, y) + if cell: + cell.isStart = True + self.start = cell + + def setExit(self, x, y): + cell = self.getCell(x, y) + if cell: + cell.isExit = True + self.exit = cell + +class MazeBuilder(ABC): + + def buildFromFile(self, filename): + pass + +class TextileMazeBuilder(MazeBuilder): + def buildFromFile(self, filename): + with open(filename, 'r', encoding='utf-8') as f: + lines = f.readlines() + + + lines = [line.rstrip('\n\r') for line in lines] + + height = len(lines) + width = len(lines[0]) if height > 0 else 0 + + + for line in lines: + if len(line) != width: + raise ValueError("все строки одинаковой длины") + + + maze = Maze(width, height) + + + for y in range(height): + for x in range(width): + char = lines[y][x] + cell = maze.getCell(x, y) + + if char == '#': + cell.isWall = True + elif char == ' ': + cell.isWall = False + elif char == 's': + cell.isWall = False + cell.isStart = True + maze.start = cell + elif char == 'e': + cell.isWall = False + cell.isExit = True + maze.exit = cell + else: + raise ValueError(f"неизв сим") + + + if maze.start is None: + raise ValueError("в лабиринте не найден старт") + if maze.exit is None: + raise ValueError("в лабиринте не найден выход") + + return maze + +class PathFindingStrategy: + def findPath(self, maze, start, exit): + pass + + +class BFSStrategy(PathFindingStrategy): + def findPath(self, maze, start, exit): + if exit is None: + return [] + queue = deque([start]) + visited = {start} + parent = {start: None} + + while queue: + current = queue.popleft() + + if current == exit: + return self._reconstruct_path(parent, start, exit) + + for neighbor in maze.getNeighbors(current): + if neighbor not in visited: + visited.add(neighbor) + parent[neighbor] = current + queue.append(neighbor) + + return [] + + def _reconstruct_path(self, parent, start, exit): + path = [] + current = exit + while current is not None: + path.append(current) + current = parent[current] + path.reverse() + return path + + +class DFSStrategy(PathFindingStrategy): + def findPath(self, maze, start, exit): + if exit is None: + return [] + stack = [start] + visited = {start} + parent = {start: None} + + while stack: + current = stack.pop() + + if current == exit: + return self._reconstruct_path(parent, start, exit) + + for neighbor in maze.getNeighbors(current): + if neighbor not in visited: + visited.add(neighbor) + parent[neighbor] = current + stack.append(neighbor) + + return [] + + def _reconstruct_path(self, parent, start, exit): + path = [] + current = exit + while current is not None: + path.append(current) + current = parent[current] + path.reverse() + return path + + +class AStrategy(PathFindingStrategy): + def _heuristic(self, cell, exit): + if exit is None: + return 0 + return abs(cell.x - exit.x) + abs(cell.y - exit.y) + + def findPath(self, maze, start, exit): + if exit is None: + return [] + open_set = [] + heapq.heappush(open_set, (0, start)) + + came_from = {start: None} + g_score = {start: 0} + + while open_set: + current = heapq.heappop(open_set)[1] + + if current == exit: + return self._reconstruct_path(came_from, start, exit) + + for neighbor in maze.getNeighbors(current): + tentative_g = g_score[current] + 1 + + if neighbor not in g_score or tentative_g < g_score[neighbor]: + came_from[neighbor] = current + g_score[neighbor] = tentative_g + f_score = tentative_g + self._heuristic(neighbor, exit) + heapq.heappush(open_set, (f_score, neighbor)) + + return [] + + def _reconstruct_path(self, came_from, start, exit): + path = [] + current = exit + while current is not None: + path.append(current) + current = came_from[current] + path.reverse() + return path + + +class SearchStats: + def __init__(self, time_ms=0, visited_cells=0, path_length=0): + self.time_ms = time_ms + self.visited_cells = visited_cells + self.path_length = path_length + + def __str__(self): + return f"Время: {self.time_ms:.3f} мс | Посещено: {self.visited_cells} | Длина пути: {self.path_length}" + + +class MazeSolver: + def __init__(self, maze): + self.maze = maze + self.strategy = None + + def setStrategy(self, strategy): + self.strategy = strategy + + def solve(self): + if self.strategy is None: + raise ValueError("Стратегия не установлена") + + + start_time = time.perf_counter() + path = self.strategy.findPath(self.maze, self.maze.start, self.maze.exit) + + end_time = time.perf_counter() + elapsed_ms = (end_time - start_time) * 1000 + + + stats = SearchStats( + time_ms=elapsed_ms, + visited_cells=len(path), + path_length=len(path) + ) + + return path, stats + +class Observer: + def update(self, event): + pass + +class ConsoleView(Observer): + def render(self, maze, player_position=None, path=None): + """отрисовка""" + os.system('cls' if os.name == 'nt' else 'clear') + + path_set = set(path) if path else set() + + for y in range(maze.height): + for x in range(maze.width): + cell = maze.getCell(x, y) + + if player_position and cell == player_position: + print('P', end='') + elif cell == maze.start: + print('S', end='') + elif cell == maze.exit: + print('E', end='') + elif cell in path_set: + print('.', end='') + elif cell.isWall: + print('#', end='') + else: + print(' ', end='') + print() + + def update(self, event): + if event['type'] == 'path_found': + print(f"длина пути {len(event['path'])}") + self.render(event['maze'], path=event['path']) + elif event['type'] == 'move': + print(f"шаг {event['step']}") + self.render(event['maze'], event['player'], event['path']) + elif event['type'] == 'maze_loaded': + print("перегрузка") + self.render(event['maze']) + + +class ObservableMazeSolver: + def __init__(self, maze): + self.maze = maze + self.strategy = None + self.observers = [] + + def attach(self, observer): + self.observers.append(observer) + + def notify(self, event): + for observer in self.observers: + observer.update(event) + + def setStrategy(self, strategy): + self.strategy = strategy + + def solve(self): + if self.strategy is None: + raise ValueError("") + + + path = self.strategy.findPath(self.maze, self.maze.start, self.maze.exit) + + self.notify({ + 'type': 'path_found', + 'maze': self.maze, + 'path': path + }) + + return path + +class Player: + def __init__(self, start_cell): + self.currentCell = start_cell + self.previousCell = None + + def moveTo(self, cell): + self.previousCell = self.currentCell + self.currentCell = cell + + def undoMove(self): + if self.previousCell: + self.currentCell, self.previousCell = self.previousCell, None + return True + return False + + +class Command: + def execute(self): + pass + + def undo(self): + pass + +class MoveCommand(Command): + def __init__(self, player, direction, maze): + self.player = player + self.dx, self.dy = direction + self.maze = maze + self.executed = False + + def execute(self): + new_x = self.player.currentCell.x + self.dx + new_y = self.player.currentCell.y + self.dy + new_cell = self.maze.getCell(new_x, new_y) + + if new_cell and new_cell.isPassable(): + self.player.moveTo(new_cell) + self.executed = True + return True + return False + + def undo(self): + if self.executed: + self.player.undoMove() + self.executed = False + return True + return False + +def clear_console(): + os.system('cls' if os.name == 'nt' else 'clear') + +def render_maze_with_player(maze, player, path=None): + path_set = set(path) if path else set() + + for y in range(maze.height): + for x in range(maze.width): + cell = maze.getCell(x, y) + + if cell == player.currentCell: + print('P', end='') + elif cell == maze.start: + print('S', end='') + elif cell == maze.exit: + print('E', end='') + elif cell in path_set: + print('.', end='') + elif cell.isWall: + print('#', end='') + else: + print(' ', end='') + print() + + +def run_game(maze, path=None): + player = Player(maze.start) + history = [] + + directions = { + 'w': (0, -1), + 's': (0, 1), + 'a': (-1, 0), + 'd': (1, 0) + } + + print(" W/A/S/D - движение, U - отмена, Q - выход") + if path: + print(f"мин путь {len(path)} шагов") + + while True: + print() + render_maze_with_player(maze, player, path) + + if player.currentCell == maze.exit: + print("\n*** выход ***") + break + + key = input("\n> ").lower() + + if key == 'q': + print("выход из игры") + break + elif key == 'u': + if history: + cmd = history.pop() + cmd.undo() + print("отмена хода") + else: + print("нет ходов") + elif key in directions: + cmd = MoveCommand(player, directions[key], maze) + if cmd.execute(): + history.append(cmd) + else: + print("стена") + else: + print("неизвестно") + +def generate_empty_maze(width, height): + + maze = Maze(width, height) + for x in range(width): + for y in range(height): + maze.getCell(x, y).isWall = False + maze.setStart(0, 0) + maze.setExit(width-1, height-1) + return maze + +def generate_maze_with_walls(width, height, wall_probability=0.3): + + maze = Maze(width, height) + for x in range(width): + for y in range(height): + if random.random() < wall_probability: + maze.getCell(x, y).isWall = True + else: + maze.getCell(x, y).isWall = False + + + maze.getCell(0, 0).isWall = False + maze.getCell(width-1, height-1).isWall = False + + maze.setStart(0, 0) + maze.setExit(width-1, height-1) + return maze + +def generate_maze_no_exit(width, height): + + maze = generate_maze_with_walls(width, height, 0.3) + + exit_cell = maze.getCell(width-1, height-1) + exit_cell.isWall = True + maze.exit = None + return maze + +def save_maze_to_file(maze, filename): + + with open(filename, 'w') as f: + for y in range(maze.height): + for x in range(maze.width): + cell = maze.getCell(x, y) + if cell == maze.start: + f.write('s') + elif cell == maze.exit: + f.write('e') + elif cell.isWall: + f.write('#') + else: + f.write(' ') + f.write('\n') + +def create_test_mazes(): + + mazes = [] + + + small = generate_maze_with_walls(10, 10, 0.2) + save_maze_to_file(small, "maze_small.txt") + mazes.append(('маленький (10x10)', small)) + + + medium = generate_maze_with_walls(50, 50, 0.3) + save_maze_to_file(medium, "maze_medium.txt") + mazes.append(('средний (50x50)', medium)) + + + large = generate_maze_with_walls(100, 100, 0.3) + save_maze_to_file(large, "maze_large.txt") + mazes.append(('большой (100x100)', large)) + + + empty = generate_empty_maze(50, 50) + save_maze_to_file(empty, "maze_empty.txt") + mazes.append(('пустой (50x50)', empty)) + + + no_exit = generate_maze_no_exit(20, 20) + save_maze_to_file(no_exit, "maze_no_exit.txt") + mazes.append(('без выхода (20x20)', no_exit)) + + return mazes + +def run_experiment(maze, strategy, name, repeats=5): + + times = [] + visited_counts = [] + path_lengths = [] + + for _ in range(repeats): + solver = MazeSolver(maze) + solver.setStrategy(strategy()) + + start_time = time.perf_counter() + path, stats = solver.solve() + end_time = time.perf_counter() + + times.append((end_time - start_time) * 1000) + visited_counts.append(len(path) if path else 0) + path_lengths.append(len(path) if path else 0) + + return { + 'лабиринт': name, + 'стратегия': strategy.__name__.replace('Strategy', ''), + 'время_ср': sum(times) / repeats, + 'время_мин': min(times), + 'время_макс': max(times), + 'посещено_ср': sum(visited_counts) / repeats, + 'длина_пути_ср': sum(path_lengths) / repeats, + 'путь_найден': path is not None and len(path) > 0 + } + + +def run_all_experiments(): + + strategies = [BFSStrategy, DFSStrategy, AStrategy] + results = [] + + + mazes = create_test_mazes() + + for maze_name, maze in mazes: + + + for strategy in strategies: + print(f" тест {strategy.__name__}...", end=" ", flush=True) + result = run_experiment(maze, strategy, maze_name) + results.append(result) + print(f"время={result['время_ср']:.2f}мс, путь={result['длина_пути_ср']:.0f}") + + + save_results_to_csv(results) + + return results + +def save_results_to_csv(results): + + filename = "resultslab.csv" + + with open(filename, 'w', newline='', encoding='utf-8-sig') as f: + writer = csv.DictWriter(f, fieldnames=[ + 'лабиринт', 'стратегия', 'время_ср', 'время_мин', 'время_макс', + 'посещено_ср', 'длина_пути_ср', 'путь_найден' + ]) + writer.writeheader() + writer.writerows(results) + + + + +def plot_results(results): + try: + import matplotlib.pyplot as plt + import numpy as np + + labyrinths = list(set(r['лабиринт'] for r in results)) + strategies = ['BFS', 'DFS', 'A'] + + + n_rows = 3 + n_cols = 2 + fig, axes = plt.subplots(n_rows, n_cols, figsize=(14, 12)) + axes = axes.flatten() + + for idx, lab in enumerate(labyrinths): + ax = axes[idx] + + times = [] + for strat in strategies: + for r in results: + if r['лабиринт'] == lab and r['стратегия'] == strat: + times.append(r['время_ср']) + break + + x = np.arange(len(strategies)) + bars = ax.bar(x, times, color=['#1a5632', '#0e5fb4', '#051f45']) + ax.set_title(f'{lab}') + ax.set_xticks(x) + ax.set_xticklabels(strategies) + ax.set_ylabel('Время (мс)') + + for bar, t in zip(bars, times): + ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5, + f'{t:.1f}', ha='center', va='bottom', fontsize=8) + + + if len(labyrinths) < len(axes): + axes[-1].set_visible(False) + + plt.tight_layout() + plt.savefig('maze_time_comparison.png', dpi=150) + plt.show() + + + + + plt.figure(figsize=(10, 6)) + + colors = ['#d8d262', '#0e5fb4', '#ed254e'] + + for idx, strat in enumerate(strategies): + lengths = [] + for lab in labyrinths: + for r in results: + if r['лабиринт'] == lab and r['стратегия'] == strat: + lengths.append(r['длина_пути_ср']) + break + + plt.plot(labyrinths, lengths, marker='o', label=strat, color=colors[idx]) # добавьте color + + + + plt.xlabel('Лабиринт') + plt.ylabel('Длина пути ') + plt.title('Сравнение длины найденного пути') + plt.legend() + plt.xticks(rotation=45) + plt.tight_layout() + plt.savefig('maze_path_length.png', dpi=150) + plt.show() + + except ImportError: + print("") + + +def print_analysis(results): + + + + strat_data = {} + for r in results: + strat = r['стратегия'] + if strat not in strat_data: + strat_data[strat] = {'time': [], 'visited': [], 'labyrinth': []} + strat_data[strat]['time'].append(r['время_ср']) + strat_data[strat]['visited'].append(r['посещено_ср']) + strat_data[strat]['labyrinth'].append(r['лабиринт']) + + + + for strat, data in strat_data.items(): + avg_time = sum(data['time']) / len(data['time']) + print(f" {strat}: среднее время {avg_time:.2f} мс") + + + print(" BFS медленный на большом лабсамый короткий путить находит") + print(" DFS быстрый, но не всегда самый короткий") + print(" A быстрый и находит самый короткий путь") + print(" без выхода лаб. стратегии самые медленные ") + print(" в пустом стратегии самые быстрые") + + +if __name__ == "__main__": + + results = run_all_experiments() + + + print_analysis(results) + + + try: + plot_results(results) + except: + print("") \ No newline at end of file diff --git a/BorisovMI/lab_2/docs/data/maze_empty.txt b/BorisovMI/lab_2/docs/data/maze_empty.txt new file mode 100644 index 0000000..d500666 --- /dev/null +++ b/BorisovMI/lab_2/docs/data/maze_empty.txt @@ -0,0 +1,50 @@ +s + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + e diff --git a/BorisovMI/lab_2/docs/data/maze_large.txt b/BorisovMI/lab_2/docs/data/maze_large.txt new file mode 100644 index 0000000..2247202 --- /dev/null +++ b/BorisovMI/lab_2/docs/data/maze_large.txt @@ -0,0 +1,100 @@ +s## # # # # # # # ### # ## # # # # # # ### # # # # # ### +# ## # ## ### ## # # ## ## # # # ### ## ## # +# ## # # # # # ## ## # # # ## # ## # # # # ## # # # # +## # # # ##### # # # # # ## # ## # # # # # # # # # # # # # + # ### ## # # # # ## ## ## # # # # # ## # + # # # # # # ## # ### ## ## # ##### # # # # # ### ## # ### # # # +# # # ## ### # # # # # ### # # # ## ##### # # + # # ### # # ## ### # # # # # ## # ## ## # ## # ## ## # # + # # # ## # # # # ## # # # # # # # # # # # ### ## # # # + # # # # # ## # # # # # ## ## ### ###### ## ## ### # + ## ## # # # # # # ### # # # ### # ## # +# # ###### # # # ## # # # ## # # # ## #### # # # + ## # # # ### # # # # # #### # # # ## # # # # + # # # # ### ## ## # # # ## # # # # # ### # # # ### # # #### # ## +# ## # # # # # # # # # # # # # # ## ### ## # # ## # + ### # # # # ## ### # # ## # # # ## # ## # ## # + ### # # # # ### # # # # # ## # # # # # ## # # ## # +# # # # ## # # ### # ## ## # ### # # ### ## # + ### ## # ## # ## # # # # # # # # # # # ####### ## + ## ## # # # # ## # # # ## ### ### # # # ### # # # # ## # ### + ### #### ### # # # # ## ## # #### # # # # # # ## # # + ### # ## ## # ## ## ## # # # ## # # ## # ## # # + # # # # # # # #### ## # # #### ## # ## ## # # # + # ## # ## # # # # ### # ## # ## # # ## # # # ## # # #### # # + # # ## # # # # # # # # # ## ## # # # ### # # + # # # # # # ## # # # ### # ## # # # # ## # # # # # # + # # # ### # # # # # ## ## # # ## # # ## # # # +## ## ### # # ## # # # # # # # # # # # # # ## ## # # # # + # # # # # # ## # # # # # # # ## + # # # # # # ## # ## # ## # # # ## ## ## ## ### # # # # # # +# # # # # # # #### # ## # # # # ## ## # # # ## # # +## # # # # # # # ###### # # ### # # ## # # # # ### ## + # # ## # # # # #### # #### # # # ## ## ## # +# # # # # # # ## # # # # # ### ### # # # # # # # + # # # # ## # # # # # ## # ## # # ## # ## ### # # + #### # # # # ## # # # # # ## ### # # # # ### # ## # + # # # # ## ## # # # # # # # # # # # # # # # ## ## # # ## + # # # # # # ## # # # ## ## # # # # # # ## # +# # ## ## ### ## # # ## # # # ## # # # # # # # # # + ## ## # # # # # # ## ### # # # ## # # ## # ### # ### ## +## ## # # # # # # # # # ## # # ## # ### # # # # + ## # # ## ## ## # # ## # # ## # # # # ## # # +## # ## # ## ## # # # # # # # # # # ### # # # # # ## # # +# ## ## # # # # # #### ## # # # # # # # # # +# # # # # # # # ## # # # # # ### # # # # #### ## ### #### + # ## # # #### # # # # #### # # # # # ### # # ### # ## ## + ## # ## # ## # # # # # # ### # # # # # ## # # # + # # # # ## # # # ### #### ## # # # # ## ## ## # + ## # ## # ## # # # # ## # # # # # # # # # # # ## # + # # ## # # # ### # ## # ## # # ### # # # # ### # + # # ## # ## #### # # # # # # # ## ## # ## ### + # ## # # ## ## # # ## # # # ### # ## # # # # # # # # + # # ## # # ## # # # # # # # # # # # ## # ### ## +# ## # # # # # # # ## # # ## ## ## # # ## ## # # ## ### ### #### + ### # # # # # # # ## # # # ## # ## # # # ## # # ## # # # # + # # # # # # # # ## ## ### # # # # # # ## # # # # +# # # # ## # ### # # # # ## # # # ### # ## ## # # # ## + # # # # # ## # ## # # # ### # ## ## # # # # # # # # + ## ### ## # # # # ## # # # #### # #### # # ## # ## # +## ## ## # # # # ## # # ## ## ### # # # # # ### # ### ## + # # ### # # # # # # # # # ## # ### # # # ### ## ## +# # ## # ## # ## ## # # # ## ## # ## # # ## + # # ### # ## ## # # ### # # # # # # ## ## # ## + # # #### # # # # # # # ### # # # # # # ## # ### # # ### ### + # # ## # # ##### # ## # # ## ## # # # ## # # # ## ## +# ### # ## # # ###### ### # ## # ## # # ## # # # # ## ## # ## # + # # # # # # # # ## ## # # # ## # # ## ## # # # # # + ## # ## ## # ### # # # # # # # # ## # # # # # ###### # ## + ## # # # # ### # # ### ## # # ## # # # # ##### # + # # ### # # # # # # ## #### # # ### # # # ## # ## + # # ## ## # ## # #### # ## # # # # # ## ## # # # # ## ## # +## # # # # ## # # ## # # # ## # # ## # # # # # # + # # # ## # # # # ## # ## # # # # # ## # # ## +# ## ## # # # # # # ### # ## # # # # # # # # # + # # ## # # # # # # # ##### ## ## ### # # ### + # # # # # # ## ## ## # # # # # # ## # ##### # ## +# # ## # # # ## # # #### # ## # # # # # ## # # # + # # # # # ## ## # ## # # # # # #### # ## + ## # # # # ## # ## ## ## # # ## # # # ## # ## # # # + ## # # # # # # # ## ### # # # ## # # ## # +### # ## # # # ## ## # ### # # # # # ### # # # ##### # + ## # # ## # ## # # # # # ## # # # ## ####### ### # # + #### # # # # # # # # # # ## # ## # # ### # ## # # # +# # # # # # # # # # ## # # ## # # # # ## # ### # # + # # # # #### ## ## # # # # ## # # # # # # ### ### # ## + #### # ## # # # ### ## # ## ## # ## # # ## # # + # # ## # # # # # # # # ## # # ## # # ### # ## + # # # # ## ## # # ## # # # # ## # ## ## + ### ## # # # ## ## ## ## # # # ## ## # # # # # # # # # ## # # # + ## # # # # # # # # # # ## #### # # ## ### ### ## # # # + # # ##### # # # ## ## # # ## ## # # ## # #### ##### # # ## ## +# # # # # # ## # # # # # # # # # # ## # +## ### # # ## ## # ## ## ## # # ## # # ### # # ## ### # + # # # ## # ## # # # ## # # # # ## # # # # + # # # # # #### # # # ## # # # ## # # # # # # # # # # +# # # ## # # ## # # ### # # ## # # ## # # ## + # # # ## # # ### # # # # # ## ## ## +# # # # ### # # # # # # # # # # # ## ## # ### # ## # # # # + # ###### # # ## ## ## # ### # # # ## # # # ##### + # ## # # # # ## # # # # # # # # #### # # e diff --git a/BorisovMI/lab_2/docs/data/maze_medium.txt b/BorisovMI/lab_2/docs/data/maze_medium.txt new file mode 100644 index 0000000..f677674 --- /dev/null +++ b/BorisovMI/lab_2/docs/data/maze_medium.txt @@ -0,0 +1,50 @@ +s # ## # # ### # ## # # # + ## # # ## ## # # # # +# # ## # # # # ## + ### # # # # # # ## ## # ## # # + # # # ## # # # # ## # # +# # # # ## # ## # # # + ## # # # # # # # ## # # +# ## # # # ## # ## # # # # # + ## # # # # ## # # ## # ## + # # # # # ## # # ## # # # + # # # # ## # # # # ## # ## # # +# ## # # # # # # # ## ## + ## # ## ### # # # ## # ## +##### ### # # # # ## # # # # + # # ### ## # ## ## #### ### + ## # # # # ### # # ## # # +# # ## # # # # # # ## + ## # # # ### # ## # # ## # # ## ## + # #### # # # # # ### # ## + # ## # ## # # ## ### ## ### # + # # ### ## # # # ## + # # ## # # # # # # # + # ## # ### #### # ## # ### ## # # + # # ## # # # # # # # + # # ##### # # # # # # # ## # ## + ## # # # # ## ## # ## ## # + # # # # # # # ## # # # + ## # # # ## # # ## # # + # ### # # # # # # # # # ### + ### # # # # # ### # # # # # ## +# # # # # ## # # # # # ## +# ## ## ## # # # # # # ## # + # #### # # # ## # ## # + ## # # # # ## # # # # # +## # ## ## # # # ## # # ## # +# # # # # # # # # # ### # # # +# # ## # # # # # ### +# # #### ## + # # ## # # ## ### # # ## +##### # # # # # # # # # # +## # # # # # # + # # ## ## # # # # ## ### # # +# # ### ## ### ### # ## # # + ## # ### # ## # # # # + # # # # # ## # # # # # +# # ## # # ## ### # # # # + # # # # # ## # ### # + ## # # ## # # # +# # ## # ### # ### # ## # ## # ## + # # # # # # # ## # # e diff --git a/BorisovMI/lab_2/docs/data/maze_no_exit.txt b/BorisovMI/lab_2/docs/data/maze_no_exit.txt new file mode 100644 index 0000000..3e2f752 --- /dev/null +++ b/BorisovMI/lab_2/docs/data/maze_no_exit.txt @@ -0,0 +1,20 @@ +s ## ### +# # # # # ## + # # # # # + # # ## + # # # # # +# # ### # # + # # # # # +# # ## ## ### + # ## # + # # ### + # # # # # + ### # # + # # # # + ## # # # # + ## # # # # ## + # # # + # # + # # # # + # # # + # # # # ## # diff --git a/BorisovMI/lab_2/docs/data/maze_path_length.png b/BorisovMI/lab_2/docs/data/maze_path_length.png new file mode 100644 index 0000000..5d3d01d Binary files /dev/null and b/BorisovMI/lab_2/docs/data/maze_path_length.png differ diff --git a/BorisovMI/lab_2/docs/data/maze_small.txt b/BorisovMI/lab_2/docs/data/maze_small.txt new file mode 100644 index 0000000..4fab8af --- /dev/null +++ b/BorisovMI/lab_2/docs/data/maze_small.txt @@ -0,0 +1,10 @@ +s # + +# + # # + # # + # # + # + # # + # +# # e diff --git a/BorisovMI/lab_2/docs/data/maze_time_comparison.png b/BorisovMI/lab_2/docs/data/maze_time_comparison.png new file mode 100644 index 0000000..415726b Binary files /dev/null and b/BorisovMI/lab_2/docs/data/maze_time_comparison.png differ diff --git a/BorisovMI/lab_2/docs/data/report2.md b/BorisovMI/lab_2/docs/data/report2.md new file mode 100644 index 0000000..bdd7597 --- /dev/null +++ b/BorisovMI/lab_2/docs/data/report2.md @@ -0,0 +1,252 @@ +# Отчёт: Задание 2 — Поиск выхода из лабиринта + +## Цель работы + +Разработать гибкую, расширяемую программу для загрузки лабиринта из файла, поиска пути от старта до выхода с возможностью выбора алгоритма, визуализации процесса и экспериментального сравнения алгоритмов + +## Выбранные паттерны и их обоснование + +### Builder + +Для загрузки лабиринта из файла был использован паттерн Builder. +Создан интерфейс: +class MazeBuilder(): +и его реализация: +class TextFileMazeBuilder(MazeBuilder): +Преимущества использования Builder: +пользоватеь не знает деталей создания лабиринта; +можно добавить новые форматы (JSON, XML, бинарный); +код загрузки изолирован от остальной программы. + +### Strategy + +Для алгоритмов поиска пути использован паттерн Strategy +Создан общий интерфейс: +class PathFindingStrategy(): +Реализованы стратегии: +BFSStrategy; +DFSStrategy; +AStrategy; +Каждая стратегия реализует собственный алгоритм поиска пути по правилам. +Преимущества паттерна: +алгоритмы можно менять во время выполнения; +код MazeSolver не зависит от конкретного алгоритма; +новые алгоритмы можно добавлять без изменения существующего кода. + +### Observer + +Для уведомления интерфейса о событиях использован паттерн Observer +Создан интерфейс: +class Observer(): +и реализация: +class ConsoleView(Observer): +MazeSolver хранит список наблюдателей и уведомляет их о событиях: +начало поиска; +окончание поиска; +перемещение игрока. +Преимущества: +логика интерфейса отделена от логики поиска; +можно легко добавить графический интерфейс; + +### Command + +Для пошагового перемещения игрока использован паттерн Command. +Создан интерфейс: +class Command(): +и реализация: +class MoveCommand(Command): +Каждая команда умеет: +execute() — выполнить действие; +undo() — отменить действие +Преимущества: +поддержка undo; +возможность расширения системы команд + +## Листинги ключевых классов + +### Паттерн Strategy + +class PathFindingStrategy: + def findPath(self, maze, start, exit): + pass + + +class BFSStrategy(PathFindingStrategy): + def findPath(self, maze, start, exit): + if exit is None: + return [] + queue = deque([start]) + visited = {start} + parent = {start: None} + + while queue: + current = queue.popleft() + + if current == exit: + return self._reconstruct_path(parent, start, exit) + + for neighbor in maze.getNeighbors(current): + if neighbor not in visited: + visited.add(neighbor) + parent[neighbor] = current + queue.append(neighbor) + + return [] +class AStrategy(PathFindingStrategy): + def _heuristic(self, cell, exit): + if exit is None: + return 0 + return abs(cell.x - exit.x) + abs(cell.y - exit.y) + + def findPath(self, maze, start, exit): + if exit is None: + return [] + open_set = [] + heapq.heappush(open_set, (0, start)) + + came_from = {start: None} + g_score = {start: 0} + + while open_set: + current = heapq.heappop(open_set)[1] + + if current == exit: + return self._reconstruct_path(came_from, start, exit) + + for neighbor in maze.getNeighbors(current): + tentative_g = g_score[current] + 1 + + if neighbor not in g_score or tentative_g < g_score[neighbor]: + came_from[neighbor] = current + g_score[neighbor] = tentative_g + f_score = tentative_g + self._heuristic(neighbor, exit) + heapq.heappush(open_set, (f_score, neighbor)) + + return [] + +### Паттерн Command + +class Command: + def execute(self): pass + def undo(self): pass + +class MoveCommand(Command): + def __init__(self, player, direction, maze): + self.player = player + self.dx, self.dy = direction + self.maze = maze + self.executed = False + + def execute(self): + new_x = self.player.currentCell.x + self.dx + new_y = self.player.currentCell.y + self.dy + new_cell = self.maze.getCell(new_x, new_y) + if new_cell and new_cell.isPassable(): + self.player.moveTo(new_cell) + self.executed = True + return True + return False + + def undo(self): + if self.executed: + self.player.undoMove() + self.executed = False + return True + return False + + + +## Результаты + +| Лабиринт | Стратегия | Время (с) | Посещено | Длина пути | Путь найден | +|---|---|---|---|---|---| +| маленький (10x10) | BFS | 0.9148200158961117 | 19.0 | 19.0 | True | +| маленький (10x10) | DFS | 0.717819994315505 | 39.0 | 39.0 | True | +| маленький (10x10) | A | 1.577159995213151 | 19.0 | 19.0 | True | +| средний (50x50) | BFS | 14.496059995144606 | 99.0 | 99.0 | True | +| средний (50x50) | DFS | 8.470179990399629 | 393.0 | 393.0 |True | +| средний (50x50) | A | 9.11291999509558 | 99.0 | 99.0 | True | +| большой (100x100) | BFS | 0.013179995585232973 | 0.0 | 0.0 | False | +| большой (100x100) | A | 0.013079994823783636 | 0.0 | 0.0 | False | +| пустой (50x50) | BFS | 29.2012800113298 | 99.0 | 99.0 | True | +| пустой (50x50) | DFS | 13.176999986171722 | 1275.0 | 1275.0 | True | +| пустой (50x50) | A | 50.366899999789894 | 99.0 | 99.0 | True | +| без выхода (20x20) | BFS | 0.004239997360855341 | 0.0 | 0.0 | False | +| без выхода (20x20) | DFS | 0.006399990525096655 | 0.0 | 0.0 | False | +| без выхода (20x20) | A | 0.008680007886141539 | 0.0 | 0.0 | False | + +### Графики + +![Сравнение длины](maze_path_length.png) + +![Сравнение времён](maze_time_comparison.png) + +## Анализ эффективности алгоритмов + +В ходе экспериментов были получены следующие результаты. + +### BFS +Преимущества: +всегда находит кратчайший путь; +простая реализация. +Недостатки: +посещает большое количество клеток; +требует много памяти. +Выходит, что наиболее эффективен в небольших невзвешенных лабиринтах. + +### DFS +Преимущества: +простая реализация; +самым быстрым находит произвольный путь. +Недостатки: +не гарантирует кратчайший путь; +может уходить в тупики. +Подходит для быстрого поиска любого решения. + +### A +Преимущества: +высокая скорость; +посещает меньше клеток; +Недостатки: +требует выбора хорошей эвристики. +Показал хорошие результаты на больших лабиринтах. + +## Анализ применимости паттернов + +### Builder +Без Builder код загрузки лабиринта был бы жёстко связан с классом Maze, а добавление нового формата потребовало бы изменения существующего кода. +Strategy +Без Strategy пришлось бы: +хранить все алгоритмы внутри одного класса; +использовать большое количество условных операторов; +изменять код MazeSolver при добавлении новых алгоритмов +Strategy помог полностью отделить алгоритмы друг от друга. + +### Observer +Без Observer логика интерфейса смешивалась бы с логикой поиска. +Это усложнило бы: +добавление GUI; +логирование; +визуализацию. + +### Command +Без Command было бы сложно реализовать: +undo; +историю действий; +расширяемую систему управления. + +## Выводы + +### В проекте были успешно реализованы: +загрузка лабиринта из файла; +несколько алгоритмов поиска пути; +визуализация; +система наблюдателей; +система команд; +экспериментальное сравнение алгоритмов. + +### Использование паттернов GoF позволило: +сделать архитектуру гибкой; +уменьшить связанность компонентов; +упростить расширение программы; +облегчить сопровождение кода. diff --git a/BorisovMI/lab_2/docs/data/resultslab.csv b/BorisovMI/lab_2/docs/data/resultslab.csv new file mode 100644 index 0000000..59c59d0 --- /dev/null +++ b/BorisovMI/lab_2/docs/data/resultslab.csv @@ -0,0 +1,16 @@ +лабиринт,стратегия,время_ср,время_мин,время_макс,посещено_ср,длина_пути_ср,путь_найден +маленький (10x10),BFS,0.9148200158961117,0.8840999798849225,0.9673000313341618,19.0,19.0,True +маленький (10x10),DFS,0.717819994315505,0.5779999773949385,0.8650000090710819,39.0,39.0,True +маленький (10x10),A,1.577159995213151,1.531599962618202,1.7019000370055437,19.0,19.0,True +средний (50x50),BFS,14.496059995144606,12.946999981068075,18.392199999652803,99.0,99.0,True +средний (50x50),DFS,8.470179990399629,7.544599997345358,9.55930002965033,393.0,393.0,True +средний (50x50),A,9.11291999509558,8.53859999915585,9.788900031708181,99.0,99.0,True +большой (100x100),BFS,0.013179995585232973,0.009100011084228754,0.026200024876743555,0.0,0.0,False +большой (100x100),DFS,0.012619991321116686,0.008300004992634058,0.026499968953430653,0.0,0.0,False +большой (100x100),A,0.013079994823783636,0.008699949830770493,0.027500034775584936,0.0,0.0,False +пустой (50x50),BFS,29.2012800113298,19.71900003263727,47.252200020011514,99.0,99.0,True +пустой (50x50),DFS,13.176999986171722,12.441499973647296,13.887099979911,1275.0,1275.0,True +пустой (50x50),A,50.366899999789894,47.1535999677144,60.296199982985854,99.0,99.0,True +без выхода (20x20),BFS,0.004239997360855341,0.002700020559132099,0.00909995287656784,0.0,0.0,False +без выхода (20x20),DFS,0.006399990525096655,0.003200024366378784,0.012699980288743973,0.0,0.0,False +без выхода (20x20),A,0.008680007886141539,0.005399982910603285,0.01810002140700817,0.0,0.0,False