2013-04-29 32 views
0

我想找到編碼一個10個整數列表(大約在1到10000之間)到一個單一的ID(我需要一個一對一的功能整數列表爲單個整數或字符串)。編碼一個優雅的編號ID列表

我試過base64(這很好,因爲它是可逆的),但結果比輸入長得多,而且很糟糕。

例如,如果我要編碼12-54-235-1223-21-765-43-763-9522-908,

的base64給我MTItNTQtMjM1LTEyMjMtMjEtNzY1LTQzLTc2My05NTIyLTkwOA ==

散列函數是壞因爲我無法輕鬆恢復輸入。

也許我可以使用這樣的事實,我只有數字作爲輸入並使用數論的事實,有人有一個想法?

回答

1

如果整數保證是小於10^9,你可以對其進行編碼爲:

[number of digits in 1st number][1st number][number of digits in 2nd number][2nd number][...] 

所以12,54,235,1223,21,765,43,763,9522,908產量21225432354122322137652433763495223908

樣品Python實現:

def numDigits(x): 
    if x < 10: 
     return 1 
    return 1 + numDigits(x/10) 

def encode(nums): 
    ret = "" 
    for number in nums: 
     ret = ret + str(numDigits(number)) + str(number) 
    return ret 

def decode(id): 
    nums = [] 
    while id != "": 
     numDigits = int(id[0]) 
     id = id[1:] #remove first char from id 
     number = int(id[:numDigits]) 
     nums.append(number) 
     id = id[numDigits:] #remove first number from id 
    return nums 

nums = [12,54,235,1223,21,765,43,763,9522,908] 
id = encode(nums) 
decodedNums = decode(id) 
print id 
print decodedNums 

結果:

21225432354122322137652433763495223908 
[12, 54, 235, 1223, 21, 765, 43, 763, 9522, 908]