0

大家好,我正在阅读 Java 编程简介这本书,其中一个练习是:

经验洗牌检查。运行计算实验以检查我们的改组代码是否像宣传的那样工作。编写一个程序 ShuffleTest,它接受命令行参数 M 和 N,对大小为 M 的数组进行 N 次混洗,在每次混洗之前用 a[i] = i 初始化,并打印一个 M×M 表,使得第 i 行给出所有 j 的 i 在位置 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 回答