我一直在研究Magic Square的形成,在阅读了算法之后,我发现在形成MagicSquare时需要遵循一定的规则。
我遵循的算法是:
block 引用>
- The magic constant will always be equal to n(n^2 + 1)/2, where n is the dimension given.
- Numbers which magicSquare consists will always be equals 1 to n*n.
- For the first element that is 1, will always be in the position (n/2, n-1).
- Other elements will be placed like (i--,j++)
The condition to be put through for placing an elements are :
a) If i < 0, then i = n-1. b) If j == n, then j = 0. c) This is a special case, if i < 0 and j=n happens at the same time, then i = 0, j = n-2. d) If the position is already occupied by some other element, then i++, j = j-2.
然后根据条件输入magicSquare内部的元素。
根据上述算法,我写下了一段代码,由于某种原因,我得到了
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at Main.generateMagicSquare(Main.java:25) at Main.main(Main.java:58)
这很奇怪。我已经检查过,感觉使用代码来获得所需的结果是安全的,但我不知道哪里出了问题。
代码
static void generateMagicSquare(int n){ int[][] magicSquare = new int[n][n]; //initialising for pos of the elem 1 int i = n/2, j = n-1; magicSquare[i][j] = 1; //the element consist by the magic square will always be equal to 1 to n*n for(int num=2; num <= n*n; num++){ //it must go like this, for any other element i--; j++; // if the element is already present if(magicSquare[i][j] != 0){ i++; j -= 2; }else{ if(i < 0) i = n-1; if(j == n) j = 0; if(i < 0 && j == n){ i = 0; j = n-2; } } magicSquare[i][j] = num; } for(int k=0; k<n; k++){ for(int l=0; l<n; l++){ System.out.print(magicSquare[k][l] + " "); } System.out.println(); } }
如有任何帮助,我们将不胜感激。谢谢。因为我可以从互联网上复制并粘贴代码,但我想以我的方式学习它,你的帮助将帮助我实现我想要的。 :)
编辑
读完异常后,我对代码做了一些修改,但仍然有一些结果没有达到要求。
这是我更新的代码 =======>
static void generateMagicSquare(int n){ int[][] magicSquare = new int[n][n]; //initialising for pos of the elem 1 int i = n/2, j = n-1; magicSquare[i][j] = 1; //the element consist by the magic square will always be equal to 1 to n*n for(int num=2; num <= n*n; num++){ //it must go like this, for any other element i--; j++; if(i < 0){ i = n-1; } if(j == n){ j = 0; } if(i < 0 && j == n){ i = 0; j = n-2; } if(magicSquare[i][j] != 0){ i++; j -= 2; }else{ magicSquare[i][j] = num; } } for(int k=0; k<n; k++){ for(int l=0; l<n; l++){ System.out.print(magicSquare[k][l] + " "); } System.out.println(); } }
我得到这个输出:
2 0 6 9 5 1 7 3 0
仍然不是正确的答案。
最佳答案
此行引发错误:
if(magicSquare[i][j] != 0)
问题是数组 magicSquare
初始化为:
int[][] magicSquare = new int[n][n];
意味着它有 n
列,索引从 0
到 n - 1
(索引从零开始) )。
变量j
初始化为
j = n-1;
以及后来的这一行:
j++;
使j
等于n
因此,当您访问 magicSquare[i][j]
时,您正在尝试访问不存在的 magicSquare[i][n]
。
关于java - Magic Square 给出 ArrayIndexOutOfBoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54419695/