Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.List;
- import java.util.Scanner;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class Main {
- private static Scanner scConsole;
- private static int[][] dots;
- private static short choose(String sQuestion, String[] Options) { // не больше 9-ти вариантов ответа
- short nChoice;
- String answer;
- StringBuilder optionsDigits = new StringBuilder();
- System.out.println(sQuestion + "\n\tВарианты: ");
- for (int i = 0; i < Options.length; i++) {
- System.out.println("\t" + (i + 1) + " - " + Options[i]);
- optionsDigits.append(i + 1);
- }
- answer = getAnythingFromConsole("", "^[" + optionsDigits + "]$", "Нужно ввести " +
- "цифру (одну из предложенных).");
- nChoice = (short) (Short.parseShort(answer) - 1);
- return nChoice;
- }
- private static String getAnythingFromConsole(String Question, String regEx, String clarification) {
- String sInput;
- String sOutput;
- String stringIfNothingIsFoundInString = "";
- boolean isIncorrect;
- boolean nothingIsFoundIsNotAllowed = findRegEx(regEx, "\\^\\$", "")[0].equals("");
- if (!nothingIsFoundIsNotAllowed) {
- stringIfNothingIsFoundInString = regEx + "++++++";
- }
- if (!Question.equals("")) {
- System.out.println(Question);
- }
- do {
- sInput = scConsole.nextLine().trim();
- sOutput = findRegEx(sInput, regEx, stringIfNothingIsFoundInString)[0];
- if (sOutput.equals(stringIfNothingIsFoundInString)) {
- System.err.println("Данные введены неверно. " + clarification + "\nПовторите попытку:");
- isIncorrect = true;
- } else {
- isIncorrect = false;
- }
- } while (isIncorrect);
- System.out.println();
- return sOutput;
- }
- private static String[] findRegEx(String sInput, String regEx, String outputIfNothingFound) {
- ArrayList<String> arrStringOutput = new ArrayList<>();
- Pattern pattern = Pattern.compile(regEx);
- Matcher matcher = pattern.matcher(sInput);
- if (matcher.find()) {
- do {
- arrStringOutput.add(matcher.group());
- } while (matcher.find());
- } else
- arrStringOutput.add(outputIfNothingFound);
- return arrStringOutput.toArray(new String[0]);
- }
- private static void showHelp() {
- short answerOnQuestion;
- do {
- answerOnQuestion = choose("Справка", new String[]{"задание", "автор", "назад"});
- switch (answerOnQuestion) {
- case 0 -> System.out.println("Задание:\n\tНа плоскости заданы n точек своими координатами. \n\t" +
- "Найти уравнение прямой, которой принадлежит наибольшее число данных точек.\n");
- case 1 -> System.out.println("Автор:\n\tПанев Александр, гр. 051007\n\tМинск, 2021\n");
- }
- } while (answerOnQuestion != 2);
- }
- private static void askForDots() {
- String onePair;
- List<MyCoordinates> listOfPairs = new ArrayList<>();
- MyCoordinates coordinates, tempCoordinates;
- int i;
- String[] tempPairStr;
- boolean isIncorrect = true;
- boolean isNotInList;
- System.out.println("Вводите пары чисел (x; y) каждую с новой строки в виде \"x y\" (например, \"213 41\").\n" +
- "Чтобы закончить ввод, нажмите Enter с пустой введённой строкой");
- do {
- do {
- onePair = getAnythingFromConsole("", "^\\s*-?0*\\d{1,3}\\s+-?0*\\d{1,3}\\s*$|^$", "Разрешены только целые числа от -999 до 999.");
- if (!onePair.equals("")) {
- tempPairStr = findRegEx(onePair, "-?0*\\d{1,3}", "");
- coordinates = new MyCoordinates(Integer.parseInt(tempPairStr[0]), Integer.parseInt(tempPairStr[1]));
- i = 0;
- isNotInList = true;
- while (i < listOfPairs.size() && isNotInList) {
- if (Arrays.equals(coordinates.toArray(), listOfPairs.get(i).toArray())) {
- isNotInList = false;
- }
- i++;
- }
- if (isNotInList) {
- listOfPairs.add(coordinates);
- } else {
- System.out.println("такие координаты уже были введены.");
- }
- }
- } while (!onePair.equals(""));
- if (listOfPairs.size() > 1) {
- isIncorrect = false;
- } else {
- System.out.println("Надо ввести хотя бы две пары координат.\n");
- }
- } while (isIncorrect);
- dots = new int[listOfPairs.size()][2];
- for (i = 0; i < listOfPairs.size(); i++) {
- dots[i] = listOfPairs.get(i).toArray();
- }
- }
- private static MyKAndB findAnswer() {
- double best_k = 0;
- int best_b = 0;
- double k;
- int b;
- int dx;
- double dy;
- int x1, y1;
- int countDots;
- int maxCountDots = 0;
- for (int i = 0; i < dots.length; i++) {
- for (int j = i + 1; j < dots.length; j++) {
- x1 = dots[i][0];
- y1 = dots[i][1];
- dx = dots[j][0] - x1;
- dy = dots[j][1] - y1;
- k = dy / dx;
- b = (int) (y1 - x1 * dy / dx);
- countDots = 2;
- for (int iter3 = j + 1; iter3 < dots.length; iter3++) {
- if (dots[iter3][1] == dots[iter3][0] * k + b) {
- countDots++;
- }
- }
- if (countDots > maxCountDots) {
- maxCountDots = countDots;
- if (k == Double.POSITIVE_INFINITY || k == Double.NEGATIVE_INFINITY) {
- best_b = x1;
- } else {
- best_b = b;
- }
- best_k = k;
- }
- }
- }
- return new MyKAndB(best_k, best_b);
- }
- private static void askForDotsAndFindAnswer() {
- askForDots();
- MyKAndB kAndB = findAnswer();
- String stringAnswer;
- if (kAndB.getK() == Double.POSITIVE_INFINITY || kAndB.getK() == Double.NEGATIVE_INFINITY) {
- stringAnswer = "x = " + kAndB.getB();
- } else {
- String strNearX = (kAndB.getK() == 0 ? "" :
- (kAndB.getK() == 1 ? "" :
- (kAndB.getK() == (int) kAndB.getK() ? Integer.toString((int) kAndB.getK()) :
- Double.toString(kAndB.getK())) + "*") + "x ");
- String strAfterX = (kAndB.getB() == 0 ? "" : (kAndB.getB() < 0 || strNearX.equals("") ? "" : "+") + kAndB.getB());
- stringAnswer = "y = " + strNearX + strAfterX;
- if (stringAnswer.equals("y = ")) {
- stringAnswer = "y = 0";
- }
- }
- System.out.println("Уравнение лучшей прямой (или одной из лучших): " + stringAnswer);
- }
- private static void mainMenu() {
- short answerOnQuestion;
- do {
- answerOnQuestion = choose("Главное меню",
- new String[]{"ввести координаты точек и получить уравнение прямой", "показать справку", "закрыть программу"});
- switch (answerOnQuestion) {
- case 0 -> askForDotsAndFindAnswer();
- case 1 -> showHelp();
- }
- } while (answerOnQuestion != 2);
- }
- public static void main(String[] args) {
- scConsole = new Scanner(System.in);
- mainMenu();
- System.out.println("До свидания");
- scConsole.close();
- }
- }
- package com.company;
- public final class MyCoordinates {
- private final int x;
- private final int y;
- public MyCoordinates(int x, int y) {
- this.x = x;
- this.y = y;
- }
- public double getX() {
- return x;
- }
- public int getY() {
- return y;
- }
- public int[] toArray() {
- return new int[]{x, y};
- }
- }
- package com.company;
- public final class MyKAndB {
- private final double k;
- private final int b;
- public MyKAndB(double k, int b) {
- this.k = k;
- this.b = b;
- }
- public double getK() {
- return k;
- }
- public int getB() {
- return b;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment