Skip to content

Instantly share code, notes, and snippets.

@devxoul
Created February 24, 2023 18:04
Show Gist options
  • Save devxoul/7ad2ab0da1f8e4590b1893754be8a313 to your computer and use it in GitHub Desktop.
Save devxoul/7ad2ab0da1f8e4590b1893754be8a313 to your computer and use it in GitHub Desktop.
Find how many numbers Hashids can cover within the minimum length.
import sys
from math import ceil, floor
from hashids import Hashids
target_length = 8
hashids = Hashids(min_length=target_length)
print(f"target_length={target_length}")
max_value = sys.maxsize
min_value = 1
last_value = None
while True:
current_value = int((min_value + max_value) / 2)
hashid = hashids.encode(current_value)
current_length = len(hashid)
print(f"Try current_value={current_value} length={current_length} hashid={hashid}")
if current_length > target_length:
max_value = floor((max_value + current_value) / 2)
else:
min_value = ceil((min_value + current_value) / 2)
if current_length == target_length and last_value == current_value:
print(f"Found! {current_value:,}")
break
last_value = current_value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment