Vanilla_Fury

laba_6_3_java

May 20th, 2021
308
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.27 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Arrays;
  5. import java.util.List;
  6. import java.util.Scanner;
  7. import java.util.regex.Matcher;
  8. import java.util.regex.Pattern;
  9.  
  10. public class Main {
  11.  
  12.     private static Scanner scConsole;
  13.     private static int[][] dots;
  14.  
  15.     private static short choose(String sQuestion, String[] Options) { // не больше 9-ти вариантов ответа
  16.         short nChoice;
  17.         String answer;
  18.         StringBuilder optionsDigits = new StringBuilder();
  19.  
  20.         System.out.println(sQuestion + "\n\tВарианты: ");
  21.         for (int i = 0; i < Options.length; i++) {
  22.             System.out.println("\t" + (i + 1) + " - " + Options[i]);
  23.             optionsDigits.append(i + 1);
  24.         }
  25.  
  26.         answer = getAnythingFromConsole("", "^[" + optionsDigits + "]$", "Нужно ввести " +
  27.                 "цифру (одну из предложенных).");
  28.         nChoice = (short) (Short.parseShort(answer) - 1);
  29.  
  30.         return nChoice;
  31.     }
  32.  
  33.     private static String getAnythingFromConsole(String Question, String regEx, String clarification) {
  34.         String sInput;
  35.         String sOutput;
  36.         String stringIfNothingIsFoundInString = "";
  37.         boolean isIncorrect;
  38.         boolean nothingIsFoundIsNotAllowed = findRegEx(regEx, "\\^\\$", "")[0].equals("");
  39.         if (!nothingIsFoundIsNotAllowed) {
  40.             stringIfNothingIsFoundInString = regEx + "++++++";
  41.         }
  42.  
  43.         if (!Question.equals("")) {
  44.             System.out.println(Question);
  45.         }
  46.  
  47.         do {
  48.             sInput = scConsole.nextLine().trim();
  49.             sOutput = findRegEx(sInput, regEx, stringIfNothingIsFoundInString)[0];
  50.             if (sOutput.equals(stringIfNothingIsFoundInString)) {
  51.                 System.err.println("Данные введены неверно. " + clarification + "\nПовторите попытку:");
  52.                 isIncorrect = true;
  53.             } else {
  54.                 isIncorrect = false;
  55.             }
  56.         } while (isIncorrect);
  57.  
  58.         System.out.println();
  59.         return sOutput;
  60.     }
  61.  
  62.     private static String[] findRegEx(String sInput, String regEx, String outputIfNothingFound) {
  63.         ArrayList<String> arrStringOutput = new ArrayList<>();
  64.         Pattern pattern = Pattern.compile(regEx);
  65.         Matcher matcher = pattern.matcher(sInput);
  66.  
  67.         if (matcher.find()) {
  68.             do {
  69.                 arrStringOutput.add(matcher.group());
  70.             } while (matcher.find());
  71.         } else
  72.             arrStringOutput.add(outputIfNothingFound);
  73.  
  74.         return arrStringOutput.toArray(new String[0]);
  75.     }
  76.  
  77.     private static void showHelp() {
  78.         short answerOnQuestion;
  79.         do {
  80.             answerOnQuestion = choose("Справка", new String[]{"задание", "автор", "назад"});
  81.             switch (answerOnQuestion) {
  82.                 case 0 -> System.out.println("Задание:\n\tНа плоскости заданы n точек своими координатами. \n\t" +
  83.                         "Найти уравнение прямой, которой принадлежит наибольшее число данных точек.\n");
  84.                 case 1 -> System.out.println("Автор:\n\tПанев Александр, гр. 051007\n\tМинск, 2021\n");
  85.             }
  86.         } while (answerOnQuestion != 2);
  87.     }
  88.  
  89.     private static void askForDots() {
  90.         String onePair;
  91.         List<MyCoordinates> listOfPairs = new ArrayList<>();
  92.         MyCoordinates coordinates, tempCoordinates;
  93.         int i;
  94.         String[] tempPairStr;
  95.         boolean isIncorrect = true;
  96.         boolean isNotInList;
  97.  
  98.         System.out.println("Вводите пары чисел (x; y) каждую с новой строки в виде \"x y\" (например, \"213 41\").\n" +
  99.                 "Чтобы закончить ввод, нажмите Enter с пустой введённой строкой");
  100.         do {
  101.             do {
  102.                 onePair = getAnythingFromConsole("", "^\\s*-?0*\\d{1,3}\\s+-?0*\\d{1,3}\\s*$|^$", "Разрешены только целые числа от -999 до 999.");
  103.                 if (!onePair.equals("")) {
  104.                     tempPairStr = findRegEx(onePair, "-?0*\\d{1,3}", "");
  105.                     coordinates = new MyCoordinates(Integer.parseInt(tempPairStr[0]), Integer.parseInt(tempPairStr[1]));
  106.                     i = 0;
  107.                     isNotInList = true;
  108.                     while (i < listOfPairs.size() && isNotInList) {
  109.                         if (Arrays.equals(coordinates.toArray(), listOfPairs.get(i).toArray())) {
  110.                             isNotInList = false;
  111.                         }
  112.                         i++;
  113.                     }
  114.  
  115.                     if (isNotInList) {
  116.                         listOfPairs.add(coordinates);
  117.                     } else {
  118.                         System.out.println("такие координаты уже были введены.");
  119.                     }
  120.                 }
  121.             } while (!onePair.equals(""));
  122.             if (listOfPairs.size() > 1) {
  123.                 isIncorrect = false;
  124.             } else {
  125.                 System.out.println("Надо ввести хотя бы две пары координат.\n");
  126.             }
  127.         } while (isIncorrect);
  128.  
  129.         dots = new int[listOfPairs.size()][2];
  130.         for (i = 0; i < listOfPairs.size(); i++) {
  131.             dots[i] = listOfPairs.get(i).toArray();
  132.         }
  133.     }
  134.  
  135.     private static MyKAndB findAnswer() {
  136.         double best_k = 0;
  137.         int best_b = 0;
  138.         double k;
  139.         int b;
  140.         int dx;
  141.         double dy;
  142.         int x1, y1;
  143.         int countDots;
  144.         int maxCountDots = 0;
  145.  
  146.         for (int i = 0; i < dots.length; i++) {
  147.             for (int j = i + 1; j < dots.length; j++) {
  148.                 x1 = dots[i][0];
  149.                 y1 = dots[i][1];
  150.                 dx = dots[j][0] - x1;
  151.                 dy = dots[j][1] - y1;
  152.                 k = dy / dx;
  153.                 b = (int) (y1 - x1 * dy / dx);
  154.                 countDots = 2;
  155.  
  156.                 for (int iter3 = j + 1; iter3 < dots.length; iter3++) {
  157.                     if (dots[iter3][1] == dots[iter3][0] * k + b) {
  158.                         countDots++;
  159.                     }
  160.                 }
  161.                 if (countDots > maxCountDots) {
  162.                     maxCountDots = countDots;
  163.                     if (k == Double.POSITIVE_INFINITY || k == Double.NEGATIVE_INFINITY) {
  164.                         best_b = x1;
  165.                     } else {
  166.                         best_b = b;
  167.                     }
  168.                     best_k = k;
  169.                 }
  170.             }
  171.         }
  172.         return new MyKAndB(best_k, best_b);
  173.     }
  174.  
  175.     private static void askForDotsAndFindAnswer() {
  176.         askForDots();
  177.         MyKAndB kAndB = findAnswer();
  178.         String stringAnswer;
  179.         if (kAndB.getK() == Double.POSITIVE_INFINITY || kAndB.getK() == Double.NEGATIVE_INFINITY) {
  180.             stringAnswer = "x = " + kAndB.getB();
  181.         } else {
  182.             String strNearX = (kAndB.getK() == 0 ? "" :
  183.                     (kAndB.getK() == 1 ? "" :
  184.                             (kAndB.getK() == (int) kAndB.getK() ? Integer.toString((int) kAndB.getK()) :
  185.                                     Double.toString(kAndB.getK())) + "*") + "x ");
  186.  
  187.             String strAfterX = (kAndB.getB() == 0 ? "" : (kAndB.getB() < 0 || strNearX.equals("") ? "" : "+") + kAndB.getB());
  188.  
  189.             stringAnswer = "y = " + strNearX + strAfterX;
  190.             if (stringAnswer.equals("y = ")) {
  191.                 stringAnswer = "y = 0";
  192.             }
  193.         }
  194.         System.out.println("Уравнение лучшей прямой (или одной из лучших): " + stringAnswer);
  195.     }
  196.  
  197.     private static void mainMenu() {
  198.         short answerOnQuestion;
  199.         do {
  200.             answerOnQuestion = choose("Главное меню",
  201.                     new String[]{"ввести координаты точек и получить уравнение прямой", "показать справку", "закрыть программу"});
  202.             switch (answerOnQuestion) {
  203.                 case 0 -> askForDotsAndFindAnswer();
  204.                 case 1 -> showHelp();
  205.             }
  206.         } while (answerOnQuestion != 2);
  207.     }
  208.  
  209.     public static void main(String[] args) {
  210.         scConsole = new Scanner(System.in);
  211.  
  212.         mainMenu();
  213.         System.out.println("До свидания");
  214.  
  215.         scConsole.close();
  216.     }
  217. }
  218.  
  219.  
  220.  
  221.  
  222.  
  223.  
  224.  
  225. package com.company;
  226.  
  227. public final class MyCoordinates {
  228.     private final int x;
  229.     private final int y;
  230.  
  231.     public MyCoordinates(int x, int y) {
  232.         this.x = x;
  233.         this.y = y;
  234.     }
  235.  
  236.     public double getX() {
  237.         return x;
  238.     }
  239.  
  240.     public int getY() {
  241.         return y;
  242.     }
  243.  
  244.     public int[] toArray() {
  245.         return new int[]{x, y};
  246.     }
  247. }
  248.  
  249.  
  250.  
  251.  
  252.  
  253.  
  254.  
  255. package com.company;
  256.  
  257. public final class MyKAndB {
  258.     private final double k;
  259.     private final int b;
  260.  
  261.     public MyKAndB(double k, int b) {
  262.         this.k = k;
  263.         this.b = b;
  264.     }
  265.  
  266.     public double getK() {
  267.         return k;
  268.     }
  269.  
  270.     public int getB() {
  271.         return b;
  272.     }
  273. }
  274.  
Advertisement
Add Comment
Please, Sign In to add comment