aboutsummaryrefslogtreecommitdiffstats
path: root/bot/utils/randomization.py
diff options
context:
space:
mode:
authorGravatar ks129 <[email protected]>2020-09-24 18:54:39 +0300
committerGravatar ks129 <[email protected]>2020-09-24 18:54:39 +0300
commita3246bd40a3a496ad155d02653d3104392d9ff8e (patch)
treefffc704f2cc09c44f4727872d8ad80bad5a10ae9 /bot/utils/randomization.py
parentTictactoe: Use __str__ instead custom display method for user/AI name display (diff)
parentMerge branch 'master' into tic-tac-toe (diff)
Merge remote-tracking branch 'origin/tic-tac-toe' into tic-tac-toe
Diffstat (limited to '')
-rw-r--r--bot/utils/randomization.py23
1 files changed, 23 insertions, 0 deletions
diff --git a/bot/utils/randomization.py b/bot/utils/randomization.py
new file mode 100644
index 00000000..8f47679a
--- /dev/null
+++ b/bot/utils/randomization.py
@@ -0,0 +1,23 @@
+import itertools
+import random
+import typing as 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: 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]