0

Java に問題があります。

n が整数であると仮定すると、アルファベットの文字の 26^n 個の組み合わせすべてを含む StringBuffer の配列を、辞書式の順序で作成したいと考えています。ArrayIndexOutOfBoundsException を取得します。

私はこのクラスを書きました:

public static StringBuffer[] creaTabellaTotale(int n, char[] a) {   


     StringBuffer[] tabella = new StringBuffer[ pow(26, n)];
     for(int w =0; w < pow(26, n); w++)
         tabella[w] = new StringBuffer("");

     for(int h = 1; h <= n ; h++){
        for(int u =0; u < pow ( 26, h-1); u++){

        for (int j = 0; j<26; j++){

            for( int x =pow(26, n-h+1)*u + pow(26, n-h)*j; x< pow(26, n-h+1)*u + pow(26, n-h)*(j+1); x++)
                tabella[x] = tabella[x].append(a[j]);
        }

        }

     }

     return tabella;
 }

ここで a[] は、アルファベット順に 26 文字を含む配列です。pow() を書き直しました。そのプロトタイプは int pow(int b, int e) です。エラーが見つかりません。

4

2 に答える 2

3

あなたの最後:

for( int x =pow(26, n-h+1)*u + pow(26, n-h)*j; x< pow(26, n-h+1)*u + pow(26, n-h)*(j+1); x++)
            tabella[x] = tabella[x].append(a[j]);

配列よりも大きなインデックスで配列にアクセスしようとしています。気付いていないかもしれませんが、int xが正確にここで配列よりも大きくなりました:

x =pow(26, n-h+1)*u + pow(26, n-h)*j

編集:

@d'alar'cop が彼のコメントで言ったように: あなたの数学演算は不完全です

于 2013-08-09T18:31:04.880 に答える
1

I'd suggest using recursion instead of normal iteration; code is much more clear and shorter - it's easier to find bugs.

String[] alphabet = { "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", "z" };
final int amount = 26; //alphabet.size()
StringBuffer[] foo = new StringBuffer[pow(amount, n)];
long counter = 0;

public void recursion(int depth, StringBuffer actual)
{
    String a = actual.toString();
    for (int i = 0; i < amount; i++)
    {
        foo[counter++] = new StringBuffer(a + alphabet[i]);
        if (depth != 1)
            recursion(depth - 1, new StringBuffer(a + alphabet[i]));
    }
}

And just call recursion(n, "").

于 2013-08-09T18:41:30.573 に答える