I wrote a small program which basically initializes the cells of a matrix of an object of type RandomPermutation1, so that it looks like this:

[1][2][3]

[4][5][6]

[7][8][0]

Then, the method shuffle() generates a large number of random moves (supposed to be 1000, but, in my case, even 5 doesn't work) of the cell 0.

The program doesn't produce any errors, but doesn't work neither (runs infinitely).

If someone could give a hint of the error, I would be very grateful.

Below you can find the MCTaRE (Minimal Complete Tested and Readable Example) of the code.

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();    
      }  
    }
有帮助吗?

解决方案

You need to put your i++ with in your while loop

or even better

while (i++ < 5)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top