我正在尝试创建一个程序,它将一遍又一遍地“创建”一系列字符,并将它们与关键字(用户或计算机未知)进行比较。如果你愿意的话,这非常类似于“蛮力”攻击,除了这将从逻辑上构建出每一个字母。
另一件事是,我暂时构建了这个代码来处理JUST 5字母单词,并将其分解为“值”2D字符串数组。我把它作为一个非常临时的解决方案,帮助从逻辑上发现我的代码正在做什么,然后再把它扔进超级动态和复杂的for循环中。
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")
任何帮助表示赞赏。我真的很难解决这个难题。
答案 0 :(得分:2)
首先,您的字母表缺少0
(零)和z
。它也有3
两次。
其次,使用36个可能字符的五个字母单词的数量是60,466,176。等式为(size of alphabet)^(length of word)
。在这种情况下,即36^5
。我运行了你的代码,它只产生176个排列。
在我的机器上,基本实现了五个嵌套for循环,每个循环遍历字母表,生成并打印所有排列需要144秒。因此,如果您获得快速结果,则应检查正在生成的内容。
当然,手动嵌套for循环并不是一个有效的解决方案,当你希望单词的长度可变时,你还有一些工作要做。但是,我的建议是关注细节并验证您的假设!
祝你好运。