# code developed in lab Thursday 1/29/2026 (week 2)

# see slides-roulette-wheel-sampling.pdf

import random

def weighted_choice(elements, weights):
    # make sure the input is valid
    assert len(elements) == len(weights), "mismatched list lengths"
    for w in weights:
        assert w >= 0, "negative weights not allowed"
    total = sum(weights)
    r = random.uniform(0, total)
    w = 0
    for i in range(0, len(elements)):
        w += weights[i]
        if w > r:
            return elements[i]
    # all weights are zero if we get here, so pick at random
    return random.choice(elements)

def test_wc(elements, weights, trials):
    counts = [0] * len(elements)
    for i in range(trials):
        x = weighted_choice(elements, weights)
        position = elements.index(x)  # find list position of x in elements
        counts[position] += 1
    print(f"counts: {counts}")
    total_percent = 0
    for i in range(len(counts)):
        percent = 100 * counts[i] / trials
        x = elements[i]
        print(f"{x}: {percent:5.2f}%")
        total_percent += percent
    print(f"Total: {total_percent:.2f}%")


# test_wc(['a', 'b', 'c', 'd', 'e', 'f'], [6, 2, 4, 7, 2, 4], 1000000)

# test_wc(['a', 'b', 'c', 'd', 'e'], [1.5, 2.5, 0, 3, 0.7], 1000000)
