2016-09-07 198 views
-4

我想從兩個獨特的字母數字字符串中生成長度爲28的唯一字母數字字符串。從兩個唯一的字符串中獲得無碰撞字符串在數學上是可能的嗎?如何從長度爲28的兩個唯一字符串中生成長度爲28的唯一字符串?

這裏是我做過什麼

ASCII_NUMBER_RANGE_START = 48; 
ASCII_ALPHABET_RANGE_START =55; 

for (int i = 0; i < firstArray.length; i++) { 
     int tempASCIIValue = (Character.getNumericValue(firstArray[i]) + Character.getNumericValue(secondArray[i])) % 35; 
     if (tempASCIIValue <= 9) { 
      FINAL_ASCII_VALUE = tempASCIIValue + ASCII_NUMBER_RANGE_START; 
     } else { 
      FINAL_ASCII_VALUE = tempASCIIValue + ASCII_ALPHABET_RANGE_START; 
     } 
     combinedArray[i] = (char) FINAL_ASCII_VALUE; 
    } 
    return new String(combinedArray); 
} 

在上面的代碼中,我不知道結果字符串是否爲唯一強作爲其母公司的字符串。

注意:所生成的字符串以具有相同的長度,任何幫助理解父串

。謝謝。

+0

你試過了什麼? – Amy

+0

比方說,連接(唯一的A,唯一的B)將始終是唯一的字符串文字。 – tpk

+0

請嘗試此鏈接 - http://www.javapractices.com/topic/TopicAction.do?Id=56 – tpk

回答

1

鑑於碰撞是不可避免的。我們可以查看哈希代碼生成等想法。在散列表中,您希望爲每個對象生成一個散列碼。理想情況下,你想要一個Perfect hash function,但這很難實現。

你可能可以使用哈希函數逃脫,參見例如Best implementation for hashCode method。一個簡單的兩個整數變量是

int generateHashCode(int a,int b) { 
    // Start with a non-zero constant. Prime is preferred 
    int result = 17; 
    // For each field multiply the previous result by a prime and add 
    result = 31 * result + a;   
    result = 31 * result + b;   
    return result; 
} 

爲了您的實施,你可以改變這個工作與字符。如果你很樂意失去一個角色,每個角色的26 + 26 + 9 = 64可能性。這意味着每個字符可以使用6位,整個輸入可以使用168位,可以使用6位整數。然後在每對整數上運行generateHashCode()方法。

+0

感謝您的支持。 –

0

您可以使用StringBuilder/StringBuffer添加兩個字符串uid(28位字母數字),並將concatinated字符串放入Set的任何實現中。集合實現將過濾出重複的元素(如果有)。

下面是示例代碼:

import java.util.LinkedHashSet; 

public class Delete1 { 
    public static void main(String[] args) { 
     LinkedHashSet<String> impl=new LinkedHashSet<String>(); 
     for (int i = 0; i < 5; i++) { 
      String uid1="[email protected]#$%^&"; 
      String uid2="[email protected]#$%^&"; 
      StringBuilder builder=new StringBuilder(); 
      builder.append(uid1); 
      builder.append(uid2); 
      impl.add(builder.toString()); 
     } 
     for (String value : impl) { 
      System.out.println(value); 
     } 
    } 
} 

雖然循環迭代5次,但輸出

[email protected]#$%^&[email protected]#$%^& 

您可以添加循環變量,創造出獨特的ID。

+0

感謝您的努力,我會試試看,並讓您知道 –

+0

實際上,我得到了這兩個字符串的concatination,我需要它的長度與父字符串的長度相同。 –

+0

@Sayak,生成的字符串必須長度爲28 – tpk

相關問題