SteveLee
SteveLee

Reputation: 11

Sorting Coordinate System

I am inputting a x and y in two separate arraylist and putting them together like a (x,y) coordinate system into a different arraylist. And then trying to sort out that new arraylist into least to greatest using Collections.sort(arraylist); However the moment that I put double digits such as(10,11) it recognizes that smaller than (6, 7)

for(int x = 0; x <=5; x ++) {  
    System.out.print("Enter X coordinate: ");  
    int playerturnColumn = playerinput.nextInt();  
    System.out.print("Enter Y Coordinate: ");  
    int playerturnRow  = playerinput.nextInt();  
    playerturnCoordinate.add(playerturnColumn + "," + playerturnRow);  
}  
    Collections.sort(playerturnCoordinate);  
    System.out.println(playerturnCoordinate);  

Your Turn Enter X coordinate: 10 Enter Y Coordinate: 11 Enter X coordinate: 2 Enter Y Coordinate: 1 Enter X coordinate: 3 Enter Y Coordinate: 5 Enter X coordinate: 2 Enter Y Coordinate: 8 Enter X coordinate: 0 Enter Y Coordinate: 1 Enter X coordinate: 9 Enter Y Coordinate: 7 [0,1, 10,11, 2,1, 2,8, 3,5, 9,7]

Upvotes: 1

Views: 54

Answers (1)

Sash Sinha
Sash Sinha

Reputation: 22420

You could create a Coordinate class that implements Comparable:

import java.util.ArrayList;
import java.util.List;
import java.util.Collections;

class Coordinate implements Comparable<Coordinate> {
  private final int x;
  private final int y;

  public Coordinate(int x, int y) {
    this.x = x;
    this.y = y;
  }

  public int getX() {
    return this.x;
  }

  public int getY() {
    return this.y;
  }

  public String toString() {
    return String.format("[%d, %d]", getX(), getY());
  }

  public double distanceFromOrigin(Coordinate c) {
    return Math.sqrt(Math.pow(c.getX(), 2) + Math.pow(c.getY(), 2));
  }

  public int compareTo(Coordinate other) {
    return Double.compare(distanceFromOrigin(this), distanceFromOrigin(other));
  }
}

class Test {
  public static void main(String[] args) {
    List<Coordinate> playerTurnCoordinates = new ArrayList<>();
    playerTurnCoordinates.add(new Coordinate(10, 11));
    playerTurnCoordinates.add(new Coordinate(2, 1));
    playerTurnCoordinates.add(new Coordinate(3, 5));
    playerTurnCoordinates.add(new Coordinate(2, 8));
    playerTurnCoordinates.add(new Coordinate(0, 1));
    playerTurnCoordinates.add(new Coordinate(9, 7));
    playerTurnCoordinates.add(new Coordinate(6, 7));
    System.out.println("Before sorting: " + playerTurnCoordinates);
    Collections.sort(playerTurnCoordinates);
    System.out.println("After sorting: " + playerTurnCoordinates);
  }
}

Output:

Before sorting: [[10, 11], [2, 1], [3, 5], [2, 8], [0, 1], [9, 7], [6, 7]]
After sorting: [[0, 1], [2, 1], [3, 5], [2, 8], [6, 7], [9, 7], [10, 11]]

Upvotes: 2

Related Questions