0

やあみんな、Javaのプログラミング入門の本を読んでいて、演習の1つはこれです:

経験的なシャッフルチェック。計算実験を実行して、シャッフルコードが宣伝どおりに機能することを確認します。コマンドライン引数MおよびNを取り、各シャッフルの前にa [i] = iで初期化されるサイズMの配列のNシャッフルを実行し、行iのようにM行M列のテーブルを出力するプログラムShuffleTestを記述します。すべてのjについて、位置jに巻き上げられた回数を示します。配列内のすべてのエントリはN/Mに近い必要があります。

さて、このコードはゼロのブロックを出力するだけです...

public class ShuffleTest2 {
  public static void main(String[] args) {
    int M = Integer.parseInt(args[0]);
    int N = Integer.parseInt(args[1]); 
    int [] deck = new int [M];

    for (int i = 0; i < M; ++i)
      deck [i] = i;

    int [][] a = new int [M][M];

    for (int i = 0; i < M; i++) {
      for (int j = 0; j < M; j++) {
        a[i][j] = 0 ;

        for(int n = 0; n < N; n++) {
          int r = i + (int)(Math.random() * (M-i));
          int t = deck[r];
          deck[r] = deck[i];
          deck[i] = t;

          for (int b = 0; b < N; b++)
          {
            for (int c = 0; c < M; c++)
              System.out.print(" " + a[b][c]);
            System.out.println();
          }
        }
      }
    }
  }
}

私は何が間違っているのですか?:(

ありがとう

4

1 に答える 1

0

それで、aは歴史のようなものですか?あなたは今、あなたが初期化したのと同じように常にゼロで満たされているので、あなたはそれに割り当てることは決してありません!forループの「シャッフル」の後、設定する必要があります

A[i][POSITION] = CARD_VALUE

つまり、i回目のシャッフルの後、カードCARD_VALUEはPOSITIONの位置にあります。すべての詳細を説明したくはありませんが、別のforループが必要になります。また、印刷用のネストされたforループは、他のすべてが実行されたときに発生する他のループから独立している必要があります。

注意深く調べる必要のあるforループに関することがいくつかあるようです。プログラムフローを手動またはデバッガーでトレースすると、これらの中括弧とコードブロックの一部を移動する必要があることに気付くでしょう。

- これを試して -

public class ShuffleTest2 {

  public static void main(String[] args) {
    int M = Integer.parseInt(args[0]);
    int N = Integer.parseInt(args[1]); 
    int [] deck = new int [M];

    int [][] a = new int [M][M]; 

    for (int i = 0; i < M; i++) {  //initialize a to all zeroes
      for (int j = 0; j < M; j++) {
        a[i][j] = 0 ; 
      }
    }

    for(int i = 0; i < N; i++)   //puts the deck in order, shuffles it, and records. N times
    {
        for (int j = 0; j < M; j++)  //order the deck
          deck[j] = j;

        for(int j = 0; j < M; j++) {       //shuffle the deck (same as yours except counter name)
          int r = j + (int)(Math.random() * (M-j));
          int t = deck[r];
          deck[r] = deck[j];
          deck[j] = t;
        }

       for(int j = 0; j < M; j++)   //record status of this deck as described
       {
           int card_at_j = deck[j];  //value of card in position j
           a[card_at_j][j]++;        //tally that card_at_j occured in position j
       }
    }  //big loop ended

    for (int b = 0; b < M; b++)  //print loop.  a is MxM, so limit of N was wrong.
    {
        for (int c = 0; c < M; c++)
        {
           System.out.print(" " + a[b][c]);
           System.out.println();
        }
    }  //print loop ended
  }  //main() ended
 } //class ended
于 2010-11-14T16:32:30.107 に答える