import matplotlib.pyplot as plt
import csv

# Читаем и усредняем данные
insert_random = {'LinkedList': [], 'HashTable': [], 'BST': []}
insert_sorted = {'LinkedList': [], 'HashTable': [], 'BST': []}
search_data = {'LinkedList': [], 'HashTable': [], 'BST': []}
delete_data = {'LinkedList': [], 'HashTable': [], 'BST': []}

with open('experiment_results.csv', 'r', encoding='utf-8') as f:
    reader = csv.reader(f)
    next(reader)
    for row in reader:
        if len(row) >= 4:
            try:
                if row[2] == 'вставка':
                    if row[1] == 'случайный':
                        insert_random[row[0]].append(float(row[3]))
                    else:
                        insert_sorted[row[0]].append(float(row[3]))
                elif row[2] == 'поиск':
                    search_data[row[0]].append(float(row[3]))
                elif row[2] == 'удаление':
                    delete_data[row[0]].append(float(row[3]))
            except:
                pass

# Усредняем
structures = ['LinkedList', 'HashTable', 'BST']
insert_random_avg = [sum(insert_random[s])/len(insert_random[s]) if insert_random[s] else 0 for s in structures]
insert_sorted_avg = [sum(insert_sorted[s])/len(insert_sorted[s]) if insert_sorted[s] else 0 for s in structures]
search_avg = [sum(search_data[s])/len(search_data[s]) if search_data[s] else 0 for s in structures]
delete_avg = [sum(delete_data[s])/len(delete_data[s]) if delete_data[s] else 0 for s in structures]

#  Вставка
plt.figure(figsize=(8, 5))
x = range(len(structures))
plt.bar([i - 0.2 for i in x], insert_random_avg, width=0.4, label='Случайный', color='blue')
plt.bar([i + 0.2 for i in x], insert_sorted_avg, width=0.4, label='Отсортированный', color='red')
plt.xticks(x, structures)
plt.ylabel('Время (сек)')
plt.title('Вставка записей')
plt.legend()
plt.show()

#  Поиск
plt.figure(figsize=(8, 5))
plt.bar(structures, search_avg, color=['blue', 'green', 'red'])
plt.ylabel('Время (сек)')
plt.title('Поиск 110 записей')
for i, v in enumerate(search_avg):
    plt.text(i, v + 0.0001, f'{v:.6f}', ha='center')
plt.show()

# Удаление
plt.figure(figsize=(8, 5))
plt.bar(structures, delete_avg, color=['blue', 'green', 'red'])
plt.ylabel('Время (сек)')
plt.title('Удаление 50 записей')
for i, v in enumerate(delete_avg):
    plt.text(i, v + 0.001, f'{v:.6f}', ha='center')
plt.show()
