Skip to content

Instantly share code, notes, and snippets.

@FestivalBobcats
Created November 19, 2011 07:02
Show Gist options
  • Save FestivalBobcats/1378576 to your computer and use it in GitHub Desktop.
Save FestivalBobcats/1378576 to your computer and use it in GitHub Desktop.
1,679,616 unique 4-character ID possibilities. Each generated in < 2ms
module Arbiter
class Identity
@@data = Arbiter.db.collection('data')
@@coll = Arbiter.db.collection('page_ids')
def initialize
@length = identity_matrix['length']
@last = identity_matrix['last']
@idx = identity_matrix['idx']
@c = '0123456789abcdefghijklmnopqrstuvwxyz'.split(//)
@mtrx = @last.split(//).map {|x| @c.index(x) }
@id = generate
end
def to_s
@id
end
def generate
new_mtrx = @mtrx.dup
# assign current const column to next character in array
new_mtrx[@idx] = (@mtrx[@idx] + 1) % @c.size
new_id = new_mtrx.map {|x| @c[x] }.join
if @@coll.find_one('_id' => new_id)
# switch to next column in matrix
@idx = update 'idx', (@idx + 1) % @length
# Go again
generate
else
@@coll.insert('_id' => new_id)
# Update last
@last = update 'last', new_id
new_id
end
end
private
def update(field, val)
(mtrx = identity_matrix)[field] = val
@@data.update({'_id' => 'identity_matrix'}, mtrx)
val
end
def identity_matrix
document = @@data.find_one('_id' => 'identity_matrix')
if !document
document = {
'_id' => 'identity_matrix',
'length' => 4,
'last' => '8a5j',
'idx' => 0
}
@@data.insert(document)
end
document
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment