Advertisement
Martina312

[НП] - Генерички кластер

Aug 22nd, 2020
2,380
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.12 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. abstract class Element{
  4.     protected long id;
  5.  
  6.     public Element(long id) {
  7.         this.id = id;
  8.     }
  9.  
  10.     public abstract double getDistance(Element el);
  11. }
  12.  
  13. class Point2D extends Element{
  14.     private float x;
  15.     private float y;
  16.  
  17.     public Point2D(long id, float x, float y) {
  18.         super(id);
  19.         this.x = x;
  20.         this.y = y;
  21.     }
  22.  
  23.     public long getId() {
  24.         return id;
  25.     }
  26.  
  27.     public float getX() {
  28.         return x;
  29.     }
  30.  
  31.     public float getY() {
  32.         return y;
  33.     }
  34.  
  35.     public double getDistance(Element el){
  36.         Point2D point = (Point2D) el;
  37.         return Math.sqrt(Math.pow((x - point.x), 2) + Math.pow((y -point.y),2));
  38.     }
  39. }
  40.  
  41. class Cluster<T extends Point2D>{
  42.     List<T> elements;
  43.  
  44.     public Cluster() {
  45.         this.elements = new ArrayList<>();
  46.     }
  47.  
  48.     public void addItem(T element){
  49.         elements.add(element);
  50.     }
  51.  
  52.     public void near(long id, int top){
  53.         T element = null;
  54.         for (T el:elements){
  55.             if (el.id == id)
  56.                 element = el;
  57.         }
  58.  
  59.         T finalElement = element;
  60.         elements.sort(Comparator.comparing(el -> el.getDistance(finalElement)));
  61.         for (int i=0; i<top; i++){
  62.             System.out.println(String.format("%d. %d -> %.3f", i+1, elements.get(i+1).id, elements.get(i+1).getDistance(finalElement)));
  63.         }
  64.     }
  65. }
  66.  
  67. public class ClusterTest {
  68.     public static void main(String[] args) {
  69.         Scanner scanner = new Scanner(System.in);
  70.         Cluster<Point2D> cluster = new Cluster<>();
  71.         int n = scanner.nextInt();
  72.         scanner.nextLine();
  73.         for (int i = 0; i < n; ++i) {
  74.             String line = scanner.nextLine();
  75.             String[] parts = line.split(" ");
  76.             long id = Long.parseLong(parts[0]);
  77.             float x = Float.parseFloat(parts[1]);
  78.             float y = Float.parseFloat(parts[2]);
  79.             cluster.addItem(new Point2D(id, x, y));
  80.         }
  81.         int id = scanner.nextInt();
  82.         int top = scanner.nextInt();
  83.         cluster.near(id, top);
  84.         scanner.close();
  85.     }
  86. }
  87.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement