Skip to content

Solution for Comparators 01 #47

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: exercises/comparators/01
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions Coordinate.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
public class Coordinate implements Comparable<Coordinate> {

private int x;
private int y;

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

public int getX() {
return x;
}

public int getY() {
return y;
}

public double getDistanceToOriginPoint() {
return Math.hypot(x, y);
}

public int compareTo(Coordinate c) {
if (getDistanceToOriginPoint() < c.getDistanceToOriginPoint()) {
return -1;
} else if (getDistanceToOriginPoint() > c.getDistanceToOriginPoint()) {
return 1;
} else {
return 0;
}
}
}
17 changes: 16 additions & 1 deletion Exercise.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
import java.util.ArrayList;
import java.util.Collections;

public class Exercise {

public static void main(String[] args) {
// implement exercise here
ArrayList<Coordinate> coordinates = new ArrayList<>();

coordinates.add(new Coordinate(3, 5));
coordinates.add(new Coordinate(7, 6));
coordinates.add(new Coordinate(2, 1));
coordinates.add(new Coordinate(6, 8));
coordinates.add(new Coordinate(1, 9));

Collections.sort(coordinates);

for (Coordinate c : coordinates) {
System.out.println(c + ": " + c.getDistanceToOriginPoint());
}
}
}