Skip to content

Instantly share code, notes, and snippets.

@fridex
Last active February 28, 2020 20:15
Show Gist options
  • Save fridex/be51f6c10b6506826b11203d908391ec to your computer and use it in GitHub Desktop.
Save fridex/be51f6c10b6506826b11203d908391ec to your computer and use it in GitHub Desktop.
Random termial with removed binomial coefficient
#!/usr/bin/env python3
# Based on https://gist.github.com/fridex/8a2442f7e187914af715968097688aa3
import math
import random
import sys
def random_termial(n: int) -> int:
"""Get index to an item from a list of size n.
The higher index of an item is, the lower probability of picking it.
"""
assert n >= 1
addition = (n * (n & 1))
nearest = n + addition
termial_of_n = ((1 + nearest) * (nearest >> 1)) - addition
choice = random.randrange(termial_of_n)
i = math.floor(-0.5 + math.sqrt(0.25 + (choice << 1)))
return n - 1 - i
def main() -> None:
if len(sys.argv) == 1:
print(f"Usage: {sys.argv[0]} [N..]", file=sys.stderr)
sys.exit(1)
for item in sys.argv[1:]:
n = int(item) # Any exception reported.
res = random_termial(n)
print(f"Random index using random termial to a list of size {n} is {res}")
__name__ == "__main__" and main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment