2017-03-05 12 views
-2

私は一連の文字を何度も "作成"してキーワード(ユーザーやコンピュータには知られていない)と比較するプログラムを作成しようとしています。これは、 "brute force"攻撃と非常によく似ていますが、これは論理的に1文字ごとに構築されます。Javaですべての文字/単語の組み合わせを試す

もう1つは、私は一時的に5文字の単語を扱うためにこのコードを作成し、それを "値"の2D文字列配列に分解したことです。私は非常に一時的な解決策としてこれを持っています。私はそれをスーパーダイナミックで複雑なfor-loopsに投げ込む前に、自分のコードが何をしているのかを論理的に発見するのに役立ちます。 (5つの文字たとえば)

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

ようになど:

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 
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が2回あります。

第2に、36の可能な文字を使用する5文字の単語の数は60,466,176です。方程式は(size of alphabet)^(length of word)です。この場合、それは36^5です。私はあなたのコードを実行し、その176個の順列しか生成しませんでした。

私のマシンでは、5つのネストされたforループの基本的な実装では、それぞれアルファベットを反復して、すべての順列を生成して出力するのに144秒かかりました。だから、あなたが速い結果を得ているなら、あなたは何が生成されているかチェックするべきです。

もちろん、手動でループを入れ子にすることは、単語の長さを可変にしたい場合には有効な解決策ではありません。しかし、私のアドバイスは細部に注意を払い、あなたの前提を検証することです!

幸運。

関連する問題