2017-03-05 50 views
-2

我正在嘗試創建一個程序,它將反覆「創建」一系列字符,並將它們與關鍵字(用戶或計算機未知)進行比較。如果你願意的話,這與「蠻力」攻擊非常相似,除非這會邏輯地構建它所能包含的每一個字母。嘗試在Java中可能的每個字母/文字組合

另一件事是,我臨時構建了這段代碼來處理JUST 5個字母的單詞,並將它分解爲一個「值」二維字符串數組。我把它作爲一個非常臨時的解決方案,幫助我邏輯地發現我的代碼在做什麼,然後再將它放入超動態和複雜的for-loops。

public class Sample{ 

static String key, keyword = "hello"; 
static String[] list = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","1","2","3","3","4","5","6","7","8","9"}; 
int keylen = 5; // Eventually, this will be thrown into a for-loop, to get dynamic "keyword" sizes. (Will test to every word, more/less than 5 characters eventually) 

public static void main(String[] args) { 

    String[] values = {"a", "a", "a", "a", "a"}; // More temporary hardcodes. If I can figure out the for loop, the rest can be set to dynamic values. 

    int changeout_pos = 0; 
    int counter = 0; 

    while(true){ 
     if (counter == list.length){ counter = 0; changeout_pos++; } // Swap out each letter we have in list, in every position once. 

     // Try to swap them. (Try/catch is temporary lazy way of forcing the computer to say "we've gone through all possible combinations") 
     try { values[changeout_pos] = list[counter]; } catch (Exception e) { break; } 

     // Add up all the values in their respectful positions. Again, will be dynamic (and in a for-loop) once figured out. 
     key = values[0] + values[1] + values[2] + values[3] + values[4]; 
     System.out.println(key); // Temporarily print it. 
     if (key.equalsIgnoreCase(keyword)){ break; } // If it matches our lovely keyword, then we're done. We've done it! 

     counter ++; // Try another letter. 
    } 

    System.out.println("Done! \nThe keyword was: " + key); // Should return what "Keyword" is. 
} 
} 

我的目標是讓輸出是這樣的:(五年字母例如)

aaaaa 
aaaab 
aaaac 
... 
aaaba 
aaabb 
aaabc 
aaabd 
... 
aabaa 
aabab 
aabac 
... 

等等等等等等。現在通過運行這個代碼,這不是我所希望的。現在,它會去:

aaaaa 
baaaa 
caaaa 
daaaa 
... (through until 9) 
9aaaa 
9baaa 
9caaa 
9daaa 
... 
99aaa 
99baa 
99caa 
99daa 
... (Until it hits 99999 without finding the "keyword") 

任何幫助表示讚賞。我真的很難解決這個難題。

+1

任何你不在字符列表中包含「0」的原因?如果你這樣做了,你可以使用'Integer.toString(value,36)'來使用它。 –

回答

2

首先,您的字母表丟失0(零)和z。它也有3兩次。

其次,使用36個可能字符的五個字母的數量是60,466,176。方程是(size of alphabet)^(length of word)。在這種情況下,即36^5。我運行了你的代碼,並且它只生成了176個排列組合。

在我的機器上,基本實現了五個嵌套for循環,每個遍歷字母表,它花費了144秒來生成和打印所有的排列。所以,如果你得到了快速的結果,你應該檢查生成的內容。

當然,手動嵌套循環並不是一個有效的解決方案,因爲當你希望單詞的長度是可變的,所以你仍然有一些工作要做。但是,我的建議是注意細節並驗證你的假設!

祝你好運。

相關問題