2016-05-02 3 views
0

Я пытаюсь создать головоломку tromino, которая использует аргументы командной строки. Пользователь вводит число от 1 до 5, что 2 будет поднято до (например, если они войдут 3, это будет 2^3), строка и столбец (который даст индекс для пустого пространства на доске). Я не могу понять рекурсивный случай. Это то, что у меня есть до сих пор. Предполагается изменить все пространство, кроме пустого пространства в число больше 0.Tromino puzzle Recursion

import java.awt.*; 
import java.util.Hashtable; 
public class Tromino{ 

public static int[][] chessBoard; 
public static int currentNum=1; 

public static void main(String args[]){ 
    int n = Integer.parseInt(args[0]); 
    int row = Integer.parseInt(args[1]); 
    int column = Integer.parseInt(args[2]); 
    int length = (int) Math.pow(2,n); 

//Check the command line arguments. 
    if(!checkArgs(args)){ 
    return;} 
    chessBoard = new int[length][length]; 
    chessBoard[row][column] = -1; 


    //Solve the puzzle. Need to define a recursive method solve and call it here. 
    recursiveMethod(length,row,column); 

    //Display the board in two ways. Assume chessBoard is the 2D array. 
    printBoard(chessBoard); 
    printBoardGUI(chessBoard);}  


public static int[][] recursiveMethod (int length,int row,int column){ 
    //base case 
    if(length == 2){ 
    for (int i=0; i<length; i++){ 
     for(int j = 0; j<length; j++){ 
      if(chessBoard[i][j]==0){ 
       System.out.println("Row " + i + "Column " + j); 
       chessBoard[i][j]=currentNum; 
      } 
     } 
    } 
    currentNum++; 

    } 
    //recursive case 
    else{ 
    //find coordinates of missing hole 
    int saveRow = row, saveColumn=column; 
    for (int x=0; x<length; x++){ 
     for(int y=0; y<length;y++){ 
      if(chessBoard[x][y] == -1){ 
       saveRow = x; 
       saveColumn = y;} 
     } 
    } 

    //Empty Space in upper left quad 
    if(saveRow < length/2 && saveColumn < length/2){ 
     // 
     System.out.print("Upper left"); 
     recursiveMethod(length/2,row,column); 

     chessBoard[length/2][length/2-1] = currentNum; 
     chessBoard[length/2][length/2] = currentNum; 
     chessBoard[length/2-1][length/2] = currentNum; 
     //increment number 
     currentNum++; 
     recursiveMethod(length/2,row,length/2); 

     recursiveMethod(length/2,length/2,column); 

     recursiveMethod(length/2,length/2,length/2); 

    } 
    //Upper Right 
    else if (saveRow<length/2 && saveColumn>= length/2){ 
     System.out.print("Upper right"); 
     recursiveMethod(length/2,row,length/2); 

     chessBoard[length/2][length/2-1] = currentNum; 
     chessBoard[length/2][length/2]= currentNum; 
     chessBoard[length/2-1][length/2-1]=currentNum; 

     currentNum++; 

     recursiveMethod(length/2,row,column); 

     recursiveMethod(length/2,length/2,column); 

     recursiveMethod(length/2,length/2,length/2); 


    } 
    //Bottom left 
    else if (saveRow>=length/2 && saveColumn<length/2){ 
     System.out.println("Bottom left"); 
     recursiveMethod(length/2,length/2,column); 

     chessBoard[length/2-1][length/2] = currentNum; 
     chessBoard[length/2][length/2] = currentNum; 
     chessBoard[length/2-1][length/2-1] = currentNum; 

     currentNum++; 

     recursiveMethod(length/2,row,column); 

     recursiveMethod(length/2,row,length/2); 

     recursiveMethod(length/2,length/2,length/2); 

    } 
    //Bottom right 
    else{ 
     System.out.println("Bottom right"); 
     recursiveMethod(length/2,length/2,length/2); 

     chessBoard[length/2-1][length/2] = currentNum; 
     chessBoard[length/2][length/2-1] = currentNum; 
     chessBoard[length/2-1][length/2-1] = currentNum; 

     currentNum++; 

     recursiveMethod(length/2,length/2,column); 

     recursiveMethod(length/2,row,length/2); 

     recursiveMethod(length/2,row,column); 

    }  

    } 
    return chessBoard; 

    } 
    public static boolean isNumber(String s) { 
    return s.matches("[-+]?\\d*\\.?\\d+"); 
    } 

    public static boolean checkArgs(String[] args){ 
    int n,row,column; 
    try{ 
    n = Integer.parseInt(args[0]); 
    row = Integer.parseInt(args[1]); 
    column = Integer.parseInt(args[2]); 
    } 
    catch (Exception e){ 
    System.out.println("You have entered an invalid argument."); 
    return false;} 
    if (n>0 && n<6 && row>=0 && 
    row < Math.pow(2,n) && 
    column >=0 && column< Math.pow(2,n)){ 
    return true;} 
    else{ 
    System.out.println("The space is out of range."); 
    return false;} 
} 
public static int getIndex(int n, int k){ 
return (int) (Math.pow(2, n-1) - 1 +(int) (k/Math.pow(2, n)) *  Math.pow(2,n)); 
} 
public static void printBoard(int[][] board){ 
    int boardLength = board.length; 

    for(int i=0; i<boardLength; i++){ 
    System.out.print(" "); 
    for(int j=0; j<boardLength; j++){ 
     System.out.print("----"); 
    } 
    System.out.println(); 
    for(int j=0; j<boardLength; j++){ 
     System.out.print(" | " + board[i][j]); 
    } 
    System.out.println(" |"); 
    } 
    System.out.print(" "); 
    for(int j=0; j<boardLength; j++){ 
    System.out.print("----"); 
    } 
    System.out.println(); 
} 
public static void printBoardGUI(int[][] board){ 
    int boardLength = board.length; 
    int width = 50; 
    int boardLengthPx = boardLength * width; 
    Hashtable<Integer, Color> colors = new Hashtable<Integer, Color>(); 
    DrawingPanel panel = new DrawingPanel(boardLengthPx, boardLengthPx); 
    panel.setBackground(Color.darkGray); 

    colors.put(0, Color.white); 

    Graphics g = panel.getGraphics(); 
    for(int i = 0; i < boardLength; i++) { 
    for(int j = 0; j < boardLength; j++) { 
     if (!colors.containsKey(board[i][j])){ 
      colors.put(board[j][i], 
      Color.getHSBColor((float)Math.random(), 
      (float)(.4 + Math.random()*0.6), 
      (float)(.2 + Math.random()*0.8))); 
     } 
     g.setColor((Color)colors.get(board[i][j]));    
     g.fillRect(i * width, j * width, width, width); 
     g.setColor(Color.black); 

     g.drawLine(i * width, j * width, i * width, (j * width) + width); 
     g.drawLine(i * width, j * width, (i * width) + width, j * width); 
    } 
    } 

}}

ответ

1

У вас есть много дополнительного кода для программы, чей основной код не работает. Подумайте больше о тестировании и написании меньше. Основная проблема вашего кода заключается в том, что он не работает с его системой координат правильно - все должно быть относительно столбец и строка. Другие проблемы, в том числе непоследовательные возвращаемые значения в вашей рекурсивной функции (нет необходимости возвращать что-либо.) И множество других небольших проблем. Я переработан основной код ниже, чтобы заставить его работать, хотя это будет необходимо реальное тестирование, прежде чем начать добавлять больше:

public class Tromino { 

    public static int[][] chessBoard; 
    public static int currentNum = 1; 

    public static void main(String args[]) { 
     // Check the command line arguments. 
     if (!checkArgs(args)) { 
      return; 
     } 

     int n = Integer.parseInt(args[0]); 
     int row = Integer.parseInt(args[1]); 
     int column = Integer.parseInt(args[2]); 
     int length = (int) Math.pow(2, n); 

     chessBoard = new int[length][length]; 

     chessBoard[row][column] = -1; 

     // Solve the puzzle. Need to define a recursive method solve and call it here. 
     recursiveMethod(length, 0, 0); 

     // Display the board in two ways. Assume chessBoard is the 2D array. 
     printBoard(chessBoard); 
    } 

    public static void recursiveMethod (int length, int row, int column) { 
     // base case 
     if (length == 2) { 
      System.out.println("Base Case"); 
      for (int i = 0; i < length; i++) { 
       for (int j = 0; j < length; j++) { 
        if (chessBoard[row + i][column + j] == 0) { 
         chessBoard[row + i][column + j] = currentNum; 
        } 
       } 
      } 

      currentNum++; 

      return; 
     } 

     // find coordinates of missing hole 
     int saveRow = row, saveColumn = column; 

     for (int x = 0; x < length; x++) { 
      for (int y = 0; y < length; y++) { 
       if (chessBoard[x][y] == -1) { 
        saveRow = x; 
        saveColumn = y; 
       } 
      } 
     } 

     // recursive cases 

     // Empty Space in upper left quad 
     if (saveRow < row + length/2 && saveColumn < column + length/2) { 

      System.out.println("Upper left"); 
      recursiveMethod(length/2, row, column); 

      chessBoard[row + length/2][column + length/2 - 1] = currentNum; 
      chessBoard[row + length/2][column + length/2] = currentNum; 
      chessBoard[row + length/2 - 1][column + length/2] = currentNum; 

      currentNum++; 

      recursiveMethod(length/2, column, row + length/2); 
      recursiveMethod(length/2, column + length/2, row); 
      recursiveMethod(length/2, column + length/2, row + length/2); 

     } 
     // Upper Right 
     else if (saveRow >= row + length/2 && saveColumn < column + length/2) { 
      System.out.println("Upper right"); 
      recursiveMethod(length/2, row, column + length/2); 

      chessBoard[row + length/2][column + length/2 - 1] = currentNum; 
      chessBoard[row + length/2][column + length/2] = currentNum; 
      chessBoard[row + length/2 - 1][column + length/2 - 1] = currentNum; 

      currentNum++; 

      recursiveMethod(length/2, row, column); 
      recursiveMethod(length/2, row + length/2, column); 
      recursiveMethod(length/2, row + length/2, column + length/2); 
     } 
     // Bottom left 
     else if (saveRow < row + length/2 && saveColumn >= column + length/2) { 
      System.out.println("Bottom left"); 
      recursiveMethod(length/2, row + length/2, column); 

      chessBoard[row + length/2 - 1][column + length/2] = currentNum; 
      chessBoard[row + length/2][column + length/2] = currentNum; 
      chessBoard[row + length/2 - 1][column + length/2 - 1] = currentNum; 

      currentNum++; 

      recursiveMethod(length/2, row, column); 
      recursiveMethod(length/2, row, column + length/2); 
      recursiveMethod(length/2, row + length/2, column + length/2); 
     } 
     // Bottom right 
     else { 
      System.out.println("Bottom right"); 
      recursiveMethod(length/2, row + length/2, column + length/2); 

      chessBoard[row + length/2 - 1][column + length/2] = currentNum; 
      chessBoard[row + length/2][column + length/2 - 1] = currentNum; 
      chessBoard[row + length/2 - 1][column + length/2 - 1] = currentNum; 

      currentNum++; 

      recursiveMethod(length/2, row + length/2, column); 
      recursiveMethod(length/2, row, column + length/2); 
      recursiveMethod(length/2, row, column); 
     } 
    } 

    public static boolean checkArgs(String[] args) { 
     int n, row, column; 
     try { 
      n = Integer.parseInt(args[0]); 
      row = Integer.parseInt(args[1]); 
      column = Integer.parseInt(args[2]); 
      } 
     catch (Exception e) { 
      System.out.println("You have entered an invalid argument."); 
      return false; 
     } 

     if (n > 0 && n < 6 && row >= 0 && row < Math.pow(2, n) && column >= 0 && column < Math.pow(2, n)) { 
      return true; 
     } 

     System.out.println("The space is out of range."); 
     return false; 
    } 

    public static void printBoard(int[][] board) { 
     int boardLength = board.length; 

     for (int i = 0; i < boardLength; i++) { 
      System.out.print(" "); 
      for (int j = 0; j < boardLength; j++) { 
       System.out.print("-----"); 
      } 
      System.out.println("-"); 
      for (int j = 0; j < boardLength; j++) { 
       System.out.printf(" | %2d", board[i][j]); 
      } 
      System.out.println(" |"); 
     } 
     System.out.print(" "); 
     for (int j = 0; j < boardLength; j++) { 
      System.out.print("-----"); 
     } 
     System.out.println("-"); 
    } 
} 

Производит:

> java Tromino 3 0 0 
Upper left 
Upper left 
Base Case 
Base Case 
Base Case 
Base Case 
Bottom left 
Base Case 
Base Case 
Base Case 
Base Case 
Upper right 
Base Case 
Base Case 
Base Case 
Base Case 
Upper left 
Base Case 
Base Case 
Base Case 
Base Case 
----------------------------------------- 
| -1 | 1 | 3 | 3 | 9 | 9 | 10 | 10 | 
----------------------------------------- 
| 1 | 1 | 2 | 3 | 9 | 8 | 8 | 10 | 
----------------------------------------- 
| 4 | 2 | 2 | 5 | 7 | 7 | 8 | 11 | 
----------------------------------------- 
| 4 | 4 | 5 | 5 | 6 | 7 | 11 | 11 | 
----------------------------------------- 
| 14 | 14 | 12 | 6 | 6 | 17 | 19 | 19 | 
----------------------------------------- 
| 14 | 13 | 12 | 12 | 17 | 17 | 18 | 19 | 
----------------------------------------- 
| 15 | 13 | 13 | 16 | 20 | 18 | 18 | 21 | 
----------------------------------------- 
| 15 | 15 | 16 | 16 | 20 | 20 | 21 | 21 | 
----------------------------------------- 
>