Max Sequence

This commit is contained in:
Oliver Hofmann 2025-03-25 20:52:19 +01:00
parent 09d81f1348
commit ecb417eba2
10 changed files with 116 additions and 58 deletions

View File

View File

@ -0,0 +1,52 @@
from utils.memory_array import MemoryArray
from utils.literal import Literal
from utils.memory_cell import MemoryCell
from utils.constants import MIN_VALUE
from utils.memory_manager import MemoryManager
def max_sequence_1(z: MemoryArray):
n = len(z)
m = MemoryCell(MIN_VALUE)
s = MemoryCell()
l = MemoryCell()
r = MemoryCell()
for i in range(n):
for j in range(i, n):
s.set(0)
for k in range(i, j):
s += z[Literal(k)]
if s > m:
m.set(s)
l.set(i)
r.set(j)
return m, l, r
def example(max_sequende_func):
z = MemoryArray(Literal(10))
for i, v in enumerate([-59, 52, 46, 14, -50, 58, -87, -77, 34, 15]):
z[Literal(i)] = Literal(v)
m, l, r = max_sequende_func(z)
print(m, l, r)
def analyze_complexity(max_sequence_func, sizes):
"""
Analysiert die Komplexität einer maximalen Teilfolgenfunktion.
:param max_sequence_func: Die Funktion, die analysiert wird.
:param sizes: Eine Liste von Eingabegrößen für die Analyse.
"""
for size in sizes:
MemoryManager.purge() # Speicher zurücksetzen
random_array = MemoryArray.create_random_array(size, -100, 100)
max_sequence_func(random_array)
MemoryManager.save_stats(size)
MemoryManager.plot_stats(["cells", "adds"])
if __name__ == '__main__':
example(max_sequence_1)
analyze_complexity(max_sequence_1, [10, 20, 30, 40, 50, 60, 70, 80, 90, 100])

3
requirements.txt Normal file
View File

@ -0,0 +1,3 @@
matplotlib
numpy
pygame

View File

@ -1,41 +1,5 @@
from literal import Literal
from utils.literal import Literal
class MinValue(Literal):
MAX_VALUE = Literal(99999999999999999999)
MIN_VALUE = Literal(-99999999999999999999)
def __init__(self):
super().__init__(0)
def __gt__(self, other):
return False
def __ge__(self, other):
return False
def __lt__(self, other):
return True
def __le__(self, other):
return True
def __eq__(self, other):
return False
class MaxValue(Literal):
def __init__(self):
super().__init__(0)
def __gt__(self, other):
return True
def __ge__(self, other):
return True
def __lt__(self, other):
return False
def __le__(self, other):
return False
def __eq__(self, other):
return False

View File

@ -2,7 +2,10 @@
class Literal:
def __init__(self, value):
"""Initialisiert Literal."""
self.value = value
if isinstance(value, Literal):
self.value = value.value
else:
self.value = value
self.read_count = 0
self.compare_count = 0

View File

@ -1,7 +1,8 @@
from literal import Literal
from memory_cell import MemoryCell
from memory_manager import MemoryManager
from utils.literal import Literal
from utils.memory_cell import MemoryCell
from utils.memory_manager import MemoryManager
from pathlib import Path
from random import randint
class MemoryArray:
@ -55,7 +56,7 @@ class MemoryArray:
size = Literal(count)
a = MemoryArray(size)
for i in a.indices():
a[i] = Literal(random.randint(min_value, max_value))
a[i] = Literal(randint(min_value, max_value))
a.reset_counters()
return a

View File

@ -1,5 +1,5 @@
from memory_manager import MemoryManager
from literal import Literal
from utils.memory_manager import MemoryManager
from utils.literal import Literal
class MemoryCell (Literal):
def __init__(self, value=None):
@ -31,7 +31,10 @@ class MemoryCell (Literal):
def set(self, new_value):
"""Schreibt einen neuen Wert in die Speicherzelle und erhöht den Schreibzähler."""
self.write_count += 1
self.value = new_value
if isinstance(new_value, Literal):
self.value = new_value.value
else:
self.value = new_value
def add(self, other):
"""Addiert den Wert der Speicherzelle mit einem anderen Wert."""
@ -180,4 +183,3 @@ if __name__ == "__main__":
print(f"Ergebnis: {a}")
print(f"a wurde {a.get_read_count()} mal gelesen und {a.get_write_count()} mal geschrieben.")
print(f"b wurde {b.get_read_count()} mal gelesen und {b.get_write_count()} mal geschrieben.")
MemoryManager.print_statistics()

View File

@ -1,6 +1,11 @@
import numpy as np
import matplotlib.pyplot as plt
class MemoryManager:
instance = None
stats = {}
@staticmethod
def get_instance():
@ -51,11 +56,40 @@ class MemoryManager:
cell.reset_counters
@staticmethod
def print_statistics():
print(f"Anzahl der Speicherzellen: {MemoryManager.count_cells()}")
print(f"Anzahl der Lesezugriffe: {MemoryManager.count_reads()}")
print(f"Anzahl der Schreibzugriffe: {MemoryManager.count_writes()}")
print(f"Anzahl der Vergleiche: {MemoryManager.count_compares()}")
def purge():
MemoryManager.instance = None
@staticmethod
def save_stats(count):
data = { "cells": MemoryManager.count_cells(),
"reads": MemoryManager.count_reads(),
"writes": MemoryManager.count_writes(),
"compares": MemoryManager.count_compares(),
"adds": MemoryManager.count_adds(),
"subs": MemoryManager.count_subs(),
"muls": MemoryManager.count_muls(),
"divs": MemoryManager.count_divs(),
"bitops": MemoryManager.count_bitops() }
MemoryManager.stats[count] = data
@staticmethod
def plot_stats(labels):
data = MemoryManager.stats
x = list(data.keys())
fig, axes = plt.subplots(len(labels), 1, figsize=(8, 4 * len(labels)), sharex=True)
if len(labels) == 1:
axes = [axes] # Falls nur ein Plot vorhanden ist, in eine Liste umwandeln
for ax, l in zip(axes, labels):
y = [data[k][l] for k in x]
ax.plot(x, y, label=l)
ax.set_ylabel(l)
ax.legend()
plt.xlabel("n")
plt.show()
def __init__(self):
self.cells = []

View File

@ -1,8 +1,7 @@
from unittest import TestCase
from literal import Literal
from memory_array import MemoryArray
from utils.literal import Literal
from utils.memory_array import MemoryArray
import random
from pathlib import Path
class TestMemoryArray(TestCase):

View File

@ -1,6 +1,6 @@
from unittest import TestCase
from memory_cell import MemoryCell
from literal import Literal
from utils.memory_cell import MemoryCell
from utils.literal import Literal
import random