2017-03-05 67 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秒来生成和打印所有的排列。所以,如果你得到了快速的结果,你应该检查生成的内容。

当然,手动嵌套循环并不是一个有效的解决方案,因为当你希望单词的长度是可变的,所以你仍然有一些工作要做。但是,我的建议是注意细节并验证你的假设!

祝你好运。

相关问题