SmnVadik

Lab 6.3 (Java)

Sep 9th, 2023
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.15 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.io.FileWriter;
  4. import java.io.IOException;
  5. import java.util.List;
  6. import java.util.ArrayList;
  7. import java.util.*;
  8.  
  9. class Point {
  10.     public double X;
  11.     public double Y;
  12. }
  13.  
  14. class LineEquation {
  15.     public double K;
  16.     public double B;
  17.  
  18.     public double DistanceToLineSquared(double x, double y) {
  19.         double distance = (K * x - y + B) / Math.sqrt(K * K + 1);
  20.         return distance * distance;
  21.     }
  22.  
  23.     public static LineEquation FromPoints(double x1, double y1, double x2, double y2) {
  24.         LineEquation line = new LineEquation();
  25.         line.K = (y2 - y1) / (x2 - x1);
  26.         line.B = y1 - line.K * x1;
  27.         return line;
  28.     }
  29. }
  30.  
  31. public class Main {
  32.     static Scanner scanner = new Scanner(System.in);
  33.     static List<Point> points = new ArrayList<>();
  34.     static int[] arrayOfPoint = new int[10];
  35.  
  36.     public static void main(String[] args) throws IOException {
  37.  
  38.         task();
  39.         int num;
  40.         do {
  41.             getInfo();
  42.             num = getNum();
  43.             getUserChoice(num);
  44.         } while (num != 0);
  45.         scanner.close();
  46.     }
  47.  
  48.     private static void task() {
  49.         System.out.println("""
  50.                На плоскости заданы 2n точек своими координатами.
  51.                Найти уравнение какой-либо прямой, делящей данное множество
  52.                точек на два подмножества по n точек.""");
  53.     }
  54.  
  55.     private static void getInfo() {
  56.         System.out.println("""
  57.                1 - Добавить точки\s
  58.                2 - Показать уравнение\s
  59.                3 - Сохранить уравнение в файл\s
  60.                4 - Загрузить данные из файла\s
  61.                0 - Нажмите чтобы выйти""");
  62.     }
  63.  
  64.     static LineEquation findDividingLine(List<Point> points)
  65.     {
  66.         int size = points.size();
  67.         if (size % 2 != 0)
  68.             System.out.println("Количество точек должно быть четным.");
  69.  
  70.         double bestError = Double.MAX_VALUE;
  71.         LineEquation bestLine = new LineEquation();
  72.  
  73.         // Перебираем все возможные пары точек для построения прямой
  74.         for (int i = 0; i < size; i++) {
  75.             for (int j = i + 1; j < size; j++) {
  76.                 // Поиск уравнения прямой через две выбранные точки
  77.                 LineEquation currentLine =
  78.                         LineEquation.FromPoints(points.get(i).X, points.get(i).Y, points.get(j).X, points.get(j).Y);
  79.  
  80.                 // Рассчитываем сумму квадратов расстояний до прямой для всех точек
  81.                 double error = 0;
  82.                 for (Point point : points) {
  83.                     error += currentLine.DistanceToLineSquared(point.X, point.Y);
  84.                 }
  85.  
  86.                 if (error < bestError) {
  87.                     bestError = error;
  88.                     bestLine = currentLine;
  89.                 }
  90.             }
  91.         }
  92.         return bestLine;
  93.     }
  94.  
  95.     private static int getNum() {
  96.         int num = 0;
  97.         boolean isCorrect;
  98.         do {
  99.             isCorrect = true;
  100.             System.out.print("Введите число: ");
  101.             try {
  102.                 num = Integer.parseInt(scanner.nextLine());
  103.             } catch (NumberFormatException e) {
  104.                 isCorrect = false;
  105.                 System.out.println("Проверьте корректность введенных данных");
  106.             }
  107.             if (isCorrect && (num < 0 || num > 4)) {
  108.                 isCorrect = false;
  109.                 System.out.println("Диапазон ввода размера от 0 до 4");
  110.             }
  111.         } while (!isCorrect);
  112.         return num;
  113.     }
  114.  
  115.     private static int getPoint(String str, int i) {
  116.         int num = 0;
  117.         boolean isCorrect;
  118.         do {
  119.             isCorrect = true;
  120.             System.out.print("Введите координату " + str + ", " + i + " точки: ");
  121.             try {
  122.                 num = Integer.parseInt(scanner.nextLine());
  123.             } catch (NumberFormatException e) {
  124.                 isCorrect = false;
  125.                 System.out.println("Проверьте корректность введенных данных");
  126.             }
  127.             if (isCorrect && (num <= 0 || num > 99)) {
  128.                 isCorrect = false;
  129.                 System.out.println("Диапазон ввода числа [0; 99]");
  130.             }
  131.         } while (!isCorrect);
  132.         return num;
  133.     }
  134.  
  135.     private static int getSize() {
  136.         int size = 0;
  137.         boolean isCorrect;
  138.         do {
  139.             isCorrect = true;
  140.             System.out.print("Введите количество n от 2 до 20, и чтобы n было кратным двум: ");
  141.             try {
  142.                 size = Integer.parseInt(scanner.nextLine());
  143.             } catch (NumberFormatException e) {
  144.                 isCorrect = false;
  145.                 System.out.println("Проверьте корректность введенных данных");
  146.             }
  147.             if (isCorrect && (size < 2 || size > 20 || size % 2 != 0)) {
  148.                 isCorrect = false;
  149.                 System.out.println("Диапазон чисел [2; 20], и число должно быть кратным двум");
  150.             }
  151.         } while (!isCorrect);
  152.         return size;
  153.     }
  154.  
  155.     private static void addPoint() {
  156.         int size = getSize();
  157.         for (int i = 0; i < size; i++){
  158.             int NumX = getPoint("X", i + 1);
  159.             int NumY = getPoint("Y", i + 1);
  160.             points.add(new Point() {{
  161.                 X = NumX;
  162.                 Y = NumY;
  163.             }});
  164.         }
  165.     }
  166.  
  167.     private static void add(int NumX, int NumY) {
  168.         points.add(new Point() {{X = NumX; Y = NumY; }});
  169.     }
  170.  
  171.     private static void outputPoint() {
  172.         if (points.size() < 2) {
  173.             System.out.println("Недостаточно точек. Минимальное количетсво 2!");
  174.             return;
  175.         }
  176.         LineEquation lineWithMostPoints = findDividingLine(points);
  177.         System.out.println("Уравнение прямой: y = " + lineWithMostPoints.K + "x + " + lineWithMostPoints.B);
  178.     }
  179.  
  180.     private static String inputPath() {
  181.         String path;
  182.         boolean isCorrect;
  183.         do {
  184.             isCorrect = true;
  185.             System.out.println("Введите полный путь к файлу");
  186.             path = scanner.nextLine();
  187.             File file = new File(path);
  188.             if (!file.exists()) {
  189.                 isCorrect = false;
  190.                 System.out.println("Неверно введен путь");
  191.             }
  192.             if (isCorrect && !file.canRead()) {
  193.                 System.out.println("Невозможно считать данные с файла");
  194.             }
  195.             if (isCorrect && !file.canWrite()) {
  196.                 System.out.println("Невозможно записать данные в файл");
  197.             }
  198.         } while (!isCorrect);
  199.         return path;
  200.     }
  201.  
  202.     private static void saveData() throws IOException {
  203.         if (points.size() < 2) {
  204.             System.out.println("Недостаточно точек. Минимальное количетсво 2!");
  205.             return;
  206.         }
  207.         String path = inputPath();
  208.         LineEquation lineWithMostPoints = findDividingLine(points);
  209.         FileWriter writer = new FileWriter(path);
  210.         writer.write("Уравнение прямой: y = " + lineWithMostPoints.K + "x + " + lineWithMostPoints.B);
  211.         writer.close();
  212.     }
  213.  
  214.     private static boolean checkDataCorrectness(String path) {
  215.         boolean isCorrect = true;
  216.         boolean isNum;
  217.         int num = 0;
  218.         int size = 0;
  219.         try {
  220.             Scanner fileReader = new Scanner(new File(path));
  221.             while(fileReader.hasNext()) {
  222.                 isNum = true;
  223.                 try {
  224.                     num = fileReader.nextInt();
  225.                 } catch (Exception e) {
  226.                     isNum = false;
  227.                 }
  228.                 if (isNum && (num >= 0 && num < 100)) {
  229.                     size++;
  230.                 }
  231.             }
  232.             if (size < 4 || size > 40) {
  233.                 isCorrect = false;
  234.             } else {
  235.                 arrayOfPoint = new int[size];
  236.             }
  237.         } catch (Exception q) {
  238.             System.out.println("Проверьте корректность данных в файле.");
  239.             isCorrect = false;
  240.         }
  241.         return isCorrect;
  242.     }
  243.  
  244.     private static void openData() throws FileNotFoundException {
  245.         String path = inputPath();
  246.         boolean IsCorrect = checkDataCorrectness(path);
  247.         if (IsCorrect) {
  248.             System.out.println("Данные были успешно считаны.");
  249.         } else {
  250.             return;
  251.         }
  252.  
  253.         boolean isNum;
  254.         int num = 0;
  255.         int size = 0;
  256.         Scanner fileReader = new Scanner(new File(path));
  257.         while(fileReader.hasNext()) {
  258.             isNum = true;
  259.             try {
  260.                 num = fileReader.nextInt();
  261.             } catch (Exception e) {
  262.                 isNum = false;
  263.             }
  264.             if (isNum && (num >= 0 && num < 100)) {
  265.                 arrayOfPoint[size] = num;
  266.                 size++;
  267.             }
  268.         }
  269.  
  270.         size = arrayOfPoint.length - arrayOfPoint.length % 2;
  271.         size = size - size % 4;
  272.  
  273.         for (int i = 0; i < size; i++) {
  274.             add(arrayOfPoint[i], arrayOfPoint[i + 1]);
  275.             i++;
  276.         }
  277.     }
  278.  
  279.     private static void getUserChoice(int num) throws IOException {
  280.         switch (num) {
  281.             case 1 -> addPoint();
  282.             case 2 -> outputPoint();
  283.             case 3 -> saveData();
  284.             case 4 -> openData();
  285.         }
  286.     }
  287.  
  288. }
Advertisement
Add Comment
Please, Sign In to add comment