我编写了一个小程序,它基本上初始化了 RandomPermutation1 类型的对象的矩阵单元,因此它看起来像这样:
[1][2][3]
[4][5][6]
[7][8][0]
然后,方法 shuffle() 会生成单元格 0 的大量随机移动(应该是 1000 次,但在我的例子中,即使 5 次也不起作用)。
该程序不会产生任何错误,但也不工作(无限运行)。
如果有人能指出错误,我将不胜感激。
下面您可以找到代码的 MCTaRE(最小完整测试和可读示例)。
import java.util.*;
public class RandomPermutation1{
private int [][] randPerm;
private int row, col;
public RandomPermutation1(int row, int column){
this.row = row;
col = column;
randPerm = new int[row][col];
int number = 1;
for (int i = 0; i < row; i++){
for (int j = 0; j < col; j++){
if (i == row - 1 && j == col - 1){
randPerm[i][j] = 0;
}
else{
randPerm[i][j] = number++;
}
}
}
}
public void shuffle(){
int r = row-1;
int c = col-1;
int i = 0;
while (i < 5){
StringBuffer strB = new StringBuffer("");
if (r > 0){strB.append("n");}
if (r < row-1){strB.append("s");}
if (c > 0){strB.append("w");}
if (c < col-1){strB.append("e");}
String s = getRandom(strB);
switch(s){
case "n":
randPerm[r][c] = randPerm[r-1][c];
randPerm[r-1][c] = 0;
r = r-1;
break;
case "s":
randPerm[r][c] = randPerm[r+1][c];
randPerm[r+1][c] = 0;
r = r+1;
break;
case "w":
randPerm[r][c] = randPerm[r][c-1];
randPerm[r][c-1] = 0;
c = c-1;
break;
case "e":
randPerm[r][c] = randPerm[r][c+1];
randPerm[r][c+1] = 0;
c = c+1;
break;
}
}
i++;
}
private static String getRandom(StringBuffer strB) {
String str = strB.toString();
int rnd = new Random().nextInt(str.length());
return str.substring(rnd, rnd+1);
}
public static void main (String[]args){
RandomPermutation1 p = new RandomPermutation1 (3, 3);
p.shuffle();
}
}
最佳答案
您需要将 i++
放入 while 循环中
甚至更好
while (i++ < 5)
关于Java 程序内存不足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21822622/