AlgoDatSoSe25/vorlesung/L07_hashtable/analyze_hashtable.py
2025-05-13 13:00:07 +02:00

61 lines
2.1 KiB
Python

import math
import random
from utils.literal import Literal
from utils.memory_cell import MemoryCell
from utils.memory_array import MemoryArray
from utils.memory_manager import MemoryManager
from vorlesung.L07_hashtable.hashtable import HashTableOpenAddressing
#Goldener Schnitt
a = Literal((math.sqrt(5) - 1) / 2)
# Hashfunktion nach multiplikativer Methode
def h(x: MemoryCell, m: Literal) -> Literal:
with MemoryCell(int(x * a)) as integer_part, MemoryCell(x * a) as full_product:
with MemoryCell(full_product - integer_part) as fractional_part:
return Literal(abs(int(fractional_part * m)))
# Quadratische Sondierung
def f(x: MemoryCell, i: Literal, m: Literal) -> Literal:
c1 = 1
c2 = 5
with MemoryCell(h(x, m)) as initial_hash, MemoryCell(c2 * int(i) * int(i)) as quadratic_offset:
with MemoryCell(initial_hash + quadratic_offset) as probe_position:
probe_position += Literal(c1 * int(i)) # Linear component
return probe_position % m
# Symmetrische quadratische Sondierung
def fs(x: MemoryCell, i: Literal, m: Literal) -> Literal:
with MemoryCell(h(x, m)) as base_hash, MemoryCell(int(i) * int(i)) as square:
if int(i) % 2 == 0: # gerades i: Vorwärtssondierung
with MemoryCell(base_hash + square) as position:
return position % m
else: # ungerades i: Rückwärtssondierung
with MemoryCell(base_hash - square) as position:
return position % m
def analyze_complexity(sizes):
"""
Analysiert die Komplexität
:param sizes: Eine Liste von Eingabegrößen für die Analyse.
"""
for size in sizes:
MemoryManager.purge() # Speicher zurücksetzen
ht = HashTableOpenAddressing(size, f)
random_array = MemoryArray.create_random_array(size, -100, 100)
for cell in random_array:
ht.insert(cell)
MemoryManager.reset()
cell = random.choice(random_array.cells)
ht.search(cell)
MemoryManager.save_stats(size)
MemoryManager.plot_stats(["cells", "compares"])
if __name__ == "__main__":
sizes = range(1, 1001, 10)
analyze_complexity(sizes)