1

ランダム数独グリッドの作成に問題があります。パズルを解くために使用した再帰パターンを変更してみました。パズル自体は 2 次元の整数配列です。これは私が持っているものです(ちなみに、この方法は最初の行をランダム化するだけではありません。最初の行をランダム化するという考えがあり、グリッド全体を実行することにしました):

public boolean randomizeFirstRow(int row, int col){
    Random rGen = new Random();

    if(row == 9){
        return true;
    }
    else{
        boolean res;
        for(int ndx = rGen.nextInt() + 1; ndx <= 9;){

            //Input values into the boxes
            sGrid[row][col] = ndx;
            //Then test to see if the value is valid
            if(this.isRowValid(row, sGrid) && this.isColumnValid(col, sGrid) && this.isQuadrantValid(row, col, sGrid)){
                // grid valid, move to the next cell
                if(col + 1 < 9){
                    res = randomizeFirstRow(row, col+1);
                }

                else{
                    res = randomizeFirstRow( row+1, 0);
                }

                //If the value inputed is valid, restart loop
                if(res == true){
                    return true;
                }
            }
        }
    }

    //If no value can be put in, set value to 0 to prevent program counting to 9
    setGridValue(row, col, 0);
    //Return to previous method in stack
    return false;
}

これにより、ArrayIndexOutOfBoundsException が異常に高いまたは低い数値 (+- 100,000) で発生します。私はそれがメソッドにどこまで入っているかを確認しようとしましたが、この行を超えることはありません:

if(this.isRowValid(row, sGrid) && this.isColumnValid(col, sGrid) && this.isQuadrantValid(row, col, sGrid))

配列インデックスがどのように高くなるかわかりません。誰でも私を助けることができますか?

4

2 に答える 2

3
 for(int ndx = rGen.nextInt() + 1; ndx <= 9;){

これは怪しく見えます。Random.nextInt()0 から 9 だけでなく、整数の全範囲内のランダムな整数を返します。

于 2011-01-13T02:49:54.753 に答える
0

あなたはこれが欲しいでしょう。

public int nextInt(int n) 戻り値: 0 (含む) と n (含まない) の間の均一に分散された疑似乱数の int 値。

于 2011-01-13T03:02:34.777 に答える