Last active
August 23, 2018 23:21
-
-
Save djfdyuruiry/29a8a8e12d25b7868cad88f411403eaf to your computer and use it in GitHub Desktop.
Pseudo unique ID generator using a combination of memory addresses, time and random number generators. IDs are unique at worst unique 55% of the time, and at best up to 95% of the time.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
MAX_ID_LENGTH = 10 | |
local generatePseudoUniqueId = function() | |
local threadAddress = tostring({}):sub(10) | |
local threadAddressLetters = threadAddress:gsub("%d", "") | |
local threadAddressNumbers = threadAddress:gsub("[a-z]", "") | |
local threadAddressNumber = tonumber(threadAddressNumbers) | |
local maxNumberWidth = MAX_ID_LENGTH - threadAddressLetters:len() | |
local maxRandomNumber = tonumber(string.rep("9", maxNumberWidth)) | |
math.randomseed(os.time() + threadAddressNumber) | |
local randomNumber = math.random(maxRandomNumber) | |
local idFormatString = string.format( "%s%d%s", "%s%0", maxNumberWidth, "d") | |
return string.format(idFormatString, threadAddressLetters, randomNumber) | |
end | |
return generatePseudoUniqueId |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local generatePseudoUniqueId = require "generatePseudoUniqueId" | |
local uniqueIdCounts = {} | |
local minUniqueIdCount = 9999999 | |
local maxUniqueIdCount = 0 | |
for i=0, 1000 do | |
local ids = {} | |
for i=0, 10000 do | |
table.insert(ids, generatePseudoUniqueId()) | |
end | |
local uniqueIdCount = 0 | |
local uniqueIds = {} | |
for _, id in ipairs(ids) do | |
if not uniqueIds[id] then | |
uniqueIdCount = uniqueIdCount + 1 | |
end | |
uniqueIds[id] = true | |
end | |
io.write(string.format("%d\t", uniqueIdCount)) | |
table.insert(uniqueIdCounts, uniqueIdCount) | |
if uniqueIdCount < minUniqueIdCount then | |
minUniqueIdCount = uniqueIdCount | |
end | |
if uniqueIdCount > maxUniqueIdCount then | |
maxUniqueIdCount = uniqueIdCount | |
end | |
end | |
print() | |
local sum = 0 | |
for _, uniqueIdCount in ipairs(uniqueIdCounts) do | |
sum = sum + uniqueIdCount | |
end | |
print(string.format("10K IDs generated 1000 times: Min unique ID count: %f | Max unique ID count: %f | Average unique ID count: %f", | |
minUniqueIdCount, | |
maxUniqueIdCount, | |
sum / #uniqueIdCounts)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment