From 434e9a65529d77a0954255781c8792de60ab28d6 Mon Sep 17 00:00:00 2001 From: Xithrius Date: Wed, 9 Sep 2020 15:49:05 -0700 Subject: Added RandomCycle utility to jump between set indexes repeatedly. --- bot/utils/randomization.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 bot/utils/randomization.py (limited to 'bot/utils/randomization.py') diff --git a/bot/utils/randomization.py b/bot/utils/randomization.py new file mode 100644 index 00000000..063d7e1f --- /dev/null +++ b/bot/utils/randomization.py @@ -0,0 +1,19 @@ +import itertools +import random +import typing as t + + +class RandomCycle: + """Cycling through jumping to random indexes in an iterable.""" + + def __init__(self, iterable: t.Iterable) -> None: + self.iterable = list(iterable) + self.index = itertools.cycle(range(len(iterable))) + + def __next__(self) -> t.Any: + idx = next(self.index) + + if idx == 0: + random.shuffle(self.iterable) + + return self.iterable[idx] -- cgit v1.2.3 From 189d2e3714cb532f00921d11a9908b39ca1d7955 Mon Sep 17 00:00:00 2001 From: Xithrius <15021300+Xithrius@users.noreply.github.com> Date: Thu, 10 Sep 2020 08:43:47 -0700 Subject: Update bot/utils/randomization.py Co-authored-by: Dennis Pham --- bot/utils/randomization.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'bot/utils/randomization.py') diff --git a/bot/utils/randomization.py b/bot/utils/randomization.py index 063d7e1f..8f47679a 100644 --- a/bot/utils/randomization.py +++ b/bot/utils/randomization.py @@ -4,7 +4,11 @@ import typing as t class RandomCycle: - """Cycling through jumping to random indexes in an iterable.""" + """ + Cycles through elements from a randomly shuffled iterable, repeating indefinitely. + + The iterable is reshuffled after each full cycle. + """ def __init__(self, iterable: t.Iterable) -> None: self.iterable = list(iterable) -- cgit v1.2.3