aboutsummaryrefslogtreecommitdiffstats
path: root/bot/utils/randomization.py
blob: 1caff3fa1ab6a404ae0859ff736b53cb556a46ba (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import itertools
import random
from collections.abc import Iterable
from typing import TypeVar

T = TypeVar("T")


class RandomCycle:
    """
    Cycles through elements from a randomly shuffled iterable, repeating indefinitely.

    The iterable is reshuffled after each full cycle.
    """

    def __init__(self, iterable: Iterable[T]):
        self.iterable = list(iterable)
        self.index = itertools.cycle(range(len(iterable)))

    def __next__(self) -> T:
        idx = next(self.index)

        if idx == 0:
            random.shuffle(self.iterable)

        return self.iterable[idx]