Skip to content

Instantly share code, notes, and snippets.

@fbparis
Last active January 11, 2016 20:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fbparis/ed1e099c4d667c8ce4a4 to your computer and use it in GitHub Desktop.
Save fbparis/ed1e099c4d667c8ce4a4 to your computer and use it in GitHub Desktop.
POC for an ordered complete Library of Babel
#!/usr/bin/python
# -*- coding: utf-8 -*-
from random import choice
from tqdm import tqdm # for the progress bar...
def get_book_from_n(n):
n_max = Base**BookLength
if n >= n_max:
return None
result = []
for i in tqdm(xrange(BookLength), total=BookLength):
result.append(n % Base)
n /= Base
return result[::-1]
def get_n_from_book(book):
n = 0
for c in tqdm(book, total=BookLength):
n = Base * n + c
return n
def get_book_location_from_n(n):
n_max = Base**BookLength
if n >= n_max:
return None
hexagone = 1 + n / 640
n = n % 640
wall = 1 + n / 160
n = n % 160
shelf = 1 + n / 32
volume = 1 + n % 32
return (hexagone, wall, shelf, volume)
def get_n_from_book_location(hexagone, wall, shelf, volume):
if (hexagone > 1 + Base**BookLength / 640) or (wall not in range(1, 5)) or (shelf not in range(1, 6)) or (volume not in range(1, 33)):
return None
return (volume - 1) + (shelf - 1) * 32 + (wall - 1) * 160 + (hexagone - 1) * 640
def get_book_from_book_location(hexagone, wall, shelf, volume):
n = get_n_from_book_location(hexagone, wall, shelf, volume)
if n is None:
return None
return get_book_from_n(n)
def scientic_notation(n):
l = log10(n)
i = 10**(l-int(l))
return "%se%d" % (i, int(l))
def display_book(book):
print "".join([Alphabet[x] for x in book])
Alphabet = " abcdefghijklmnopqrstuvwxyz,."
BookLength = 3200 #* 410 # 3200*410 is OK but may be very slow, we'll use pages instead of books so
Base = len(Alphabet)
Ord = range(Base)
print "generating a random book..."
book = [choice(Ord) for x in xrange(BookLength)]
print
display_book(book) # Don't if BookLength is too huge :)
print
print "retrieving book's reference"
n = get_n_from_book(book)
hexagone, wall, shelf, volume = get_book_location_from_n(n)
print "book is located on hexagone %s, wall %d, shelf %d, volume %d" % (scientic_notation(hexagone), wall, shelf, volume)
print "checking if book location is matching reference"
if get_n_from_book_location(hexagone, wall, shelf, volume) == n:
print "YES :)"
else:
print "NO :("
print "checking if generated book is matching reference"
if get_book_from_n(n) == book:
print "YES :)"
else:
print "NO :("
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment