Home > database >  Get the previous element of an index from a Point list
Get the previous element of an index from a Point list

Time:12-18

I have a Point list that stores (x, y) values. The list is this

List<Point> path = new ArrayList<>();

However, I want to be able to get the previous index of a specific index from that list. For example I have this Point list :

[(4,4), (1,4), (2,3), (0,1)]

How can I get the previous index of (2,3), that would the (1,4),(4,4)? Any help?

CodePudding user response:

You need to override the equals(Object obj) method so that we can perform search.

class Point {

  public int x, y;
  
  public Point(int x, int y){ this.x=x; this.y=y;}
        
  public boolean equals(Object o){
    if (o instanceof Point){
      Point p = (Point) o;
      return x == p.x && y == p.y;
    }
    return false;
  }
        
  public String toString(){
    return String.format("(%d,%d)", x,y);
  }
}

indexOf() will return the index where p is found. Or you could use List.indexOf() instead.

static int indexOf(List<Point> path, Point p){
  for(int i=0; i<path.size(); i  )
    if (path.get(i).equals(p)) return i;
  return -1;
} 

Find the index of the point Every point before that point are previous points.

public static void main(String[] args) {
        
  List<Point> path = new ArrayList<>(
                List.of(new Point(0,0), new Point(1,1), 
                        new Point(2,2), new Point(3,3)));
        
  int index = indexOf(path, new Point(2,2));
        
  List<Point> prevs = new ArrayList<>();

  for(int i=0; i<index; i  )
    prevs.add(path.get(i));
        
  System.out.println(prevs);
}

Output:

[(0,0), (1,1)]

CodePudding user response:

You could do something like this:

 // Define the point or get the point that you are searching for some different way
Point x = Point(2,3)
int previousIndex = path.indexOf(x) - 1;

// Make sure we are not out of bounds
if (previousIndex >= 0){
   return path.get(previousIndex)
   // Would return (1, 4)
}

Make use of indexOf and make sure you are not out of bounds. That is pretty much all there is to it. If you want to get all previous points you could do something like this

new ArrayList(paths.subList(0 ,previousIndex 1))
  • Related