How to remove the last element from an array?

Now I am working with recursive return, my task is to find the longest path in the maze, the mass is represented as a field covered by coordinates, and the coordinates of the walls are sick in the file. I made a parser to analyze the input file and build walls, but I also saved these coordinates in an array of coordinates of the object type, to check if the next snake fragment can be moved to the next field, I created this method, now I realized that I will need a method to remove the last coordinate from the array, when I use backtracking, how can I do this? The goal is not to use array lists or linked lists only arrays! Thanks!

public class Coordinate { int xCoord; int yCoord; Coordinate(int x,int y) { this.xCoord=x; this.yCoord=y; } public int getX() { return this.xCoord; } public int getY() { return this.yCoord; } public String toString() { return this.xCoord + "," + this.yCoord; } } 

AND

 public class Row { static final int MAX_NUMBER_OF_COORD=1000; Coordinate[] coordArray; int numberOfElements; Row(){ coordArray = new Coordinate[MAX_NUMBER_OF_COORD]; numberOfElements=0; } void add(Coordinate toAdd) { coordArray[numberOfElements]=toAdd; numberOfElements +=1; } boolean ifPossible(Coordinate c1){ for(int i=0;i<numberOfElements;i++){ if(coordArray[i].xCoord==c1.xCoord && coordArray[i].yCoord==c1.yCoord){ return false; } } return true; } } 
+8
java arrays recursion backtracking
source share
3 answers

Since Java arrays do not change, you have to copy everything into a new, shorter array.

 Arrays.copyOf(original, original.length-1) 
+41
source share

I know his very old thread. However, the approved answer itself did not help me. And here is how I resolved it.

Create a method like this:

 String[] sliceArray(String[] arrayToSlice, int startIndex, int endIndex) throws ArrayIndexOutOfBoundsException { if (startIndex < 0) throw new ArrayIndexOutOfBoundsException("Wrong startIndex = " + startIndex); if (endIndex >= arrayToSlice.length) throw new ArrayIndexOutOfBoundsException("Wrong endIndex = " + endIndex); if (startIndex > endIndex) { // Then swap them! int x = startIndex; startIndex = endIndex; endIndex = x; } ArrayList<String> newArr = new ArrayList<>(); Collections.addAll(newArr, arrayToSlice); for (int i = 0; i < arrayToSlice.length; i++) { if (!(i >= startIndex && i <= endIndex)) // If not with in the start & end indices, remove the index newArr.remove(i); } return newArr.toArray(new String[newArr.size()]); } 

Then it is called like this:

 String lines[] = {"One", "Two", "Three", "Four", "Five"}; lines = sliceArray(lines, 0, 3); 

This will lead to:

 "One", "Two", "Three", "Four" 

Now I can slice the array in any way I want!

 lines = sliceArray(lines, 2, 3); 

This will lead to:

 "Three", "Four" 
+2
source share
 Arrays.asList(ARRAY_NAME).remove(ARRAY_NAME.length) 
-one
source share

All Articles