我编写了一个小程序,它基本上初始化了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();
}
}
答案 0 :(得分:4)
您需要将i++
放入while循环
甚至更好
while (i++ < 5)