# Tactiverge Academy — companion code for "Algorithms and complexity"
# Lesson: https://tactiverge.win/academy/computational-engineering/engineering-algorithms/algorithms-and-complexity/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
def largest(values):
    best = values[0]
    comparisons = 0
    for v in values[1:]:
        comparisons += 1
        if v > best:
            best = v
    return best, comparisons

print(largest([3.2, 7.9, 1.4, 7.1, 5.5]))


# ── Example 2 ────────────────────────────────────────
def count_pair_checks(n):
    checks = 0
    for i in range(n):
        for j in range(i + 1, n):
            checks += 1
    return checks

for n in [10, 100, 1000]:
    print(f"{n:5d} obstacles: {count_pair_checks(n):7d} checks")


# ── Example 3 ────────────────────────────────────────
import math

print(f"{'n':>9} {'log2 n':>7} {'n log2 n':>12} {'n²':>15}")
for n in [10, 1000, 1_000_000]:
    print(f"{n:>9} {math.log2(n):>7.1f} {n * math.log2(n):>12.0f} {n * n:>15}")


# ── Example 4 ────────────────────────────────────────
def has_duplicate_pairs(ids):
    """Compare every pair: O(n²)."""
    steps = 0
    for i in range(len(ids)):
        for j in range(i + 1, len(ids)):
            steps += 1
            if ids[i] == ids[j]:
                return True, steps
    return False, steps

def has_duplicate_set(ids):
    """Remember what we have seen in a set: O(n)."""
    seen = set()
    steps = 0
    for x in ids:
        steps += 1
        if x in seen:
            return True, steps
        seen.add(x)
    return False, steps

ids = list(range(2000))      # 2000 different IDs: the worst case
print(has_duplicate_pairs(ids))
print(has_duplicate_set(ids))
