Skip to content

Instantly share code, notes, and snippets.

@tdsmith
Created April 30, 2020 19:49
Show Gist options
  • Save tdsmith/f452329d6373bbfb58aa961396a50ecd to your computer and use it in GitHub Desktop.
Save tdsmith/f452329d6373bbfb58aa961396a50ecd to your computer and use it in GitHub Desktop.
from hashlib import sha256
from json import dumps
from math import floor
from uuid import uuid4
def evalute(input, bucket_start, bucket_width, n_buckets):
value = sha256(dumps(input).replace(" ", "").encode("utf-8")).hexdigest()[:12]
wrapped_start = bucket_start % n_buckets
end = wrapped_start + bucket_width
if end > n_buckets:
return (
in_bucket(value, 0, end % n_buckets, n_buckets) or
in_bucket(value, wrapped_start, n_buckets, n_buckets)
)
return in_bucket(value, wrapped_start, end, n_buckets)
def in_bucket(value, bucket_start, bucket_end, n_buckets):
min_hash = fraction_to_key(bucket_start / n_buckets)
max_hash = fraction_to_key(bucket_end / n_buckets)
return min_hash <= value < max_hash
def fraction_to_key(f):
assert 0 <= f <= 1
return '%012x' % int(f * ((2 ** 48) - 1))
found = False
while not found:
uuid = str(uuid4())
found = evalute(["global-v1", uuid], 9645, 200, 10000)
print(uuid)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment