-4

this is a method that return array have all the positions that a knight(in chess) make in one move , the problem that i put the size of array 8 , the chess board is (8x8) , the problem that , example : if the knight at position (1,1) this method will return {(2,3),(3,2),null,null,null,null,null,null} , i want it to return this {(2,3),(3,2)} . without using arraylist

public Position[] moves(Position p) {
    Position[] positions = new Position[8];
    int row = p.getRow();
    int col = p.getCol();

    int[][] moves = {{-1,-2},{1,-2},{-1,2},{1,2},{-2,-1},{-2,1},{2,-1},{2,1}};

        for (int k=0 ; k< moves.length;k++) {
            int newCol = col + moves[k][1];
            int newRow = row + moves[k][0];
            if(newCol >= 1 && newCol<= 8 && newRow >= 1 && newRow <= 8)
            {
                positions[k] = new Position(newRow, newCol);
            }
            else
                positions[k] = null ;
        }
    return positions;
}
rana
  • 1
  • 1

1 Answers1

1

If you don't want to use an ArrayList you can keep track of the number of moves possible, create a new double[] with that many elements, copy the data into it and return that new array.

java.util.Arrays.copyOfRange may prove useful.

Chris
  • 26,361
  • 5
  • 21
  • 42
  • thank you you helped me , i modifed my method to first count the number of valid moves the knight can make, and then create an array of that size . – rana Apr 10 '23 at 02:39