Advertisement
altervisi0n

Untitled

Jun 30th, 2023
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 14.09 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.io.*;
  4. import java.util.ArrayList;
  5. import java.util.Scanner;
  6.  
  7. public class Main {
  8.  
  9.     private static final Scanner scanner = new Scanner(System.in);
  10.  
  11.     private static final String ANSI_RED = "\u001B[31m";
  12.     private static final String ANSI_RESET = "\u001b[0m";
  13.     private static final String ANSI_YELLOW = "\u001B[33m";
  14.     private static final String ANSI_CYAN = "\u001B[36m";
  15.  
  16.     private static final int MIN_VALUE = 2;
  17.     private static final int MAX_VALUE = 99;
  18.     private static final int MIN_CHOICE_VALUE = 1;
  19.     private static final int MAX_CHOICE_VALUE = 2;
  20.  
  21.     public static void main(String[] args) {
  22.         System.out.println(ANSI_YELLOW + "Эта программа преобразовывает списки инцидентности в матрицу инциденций.");
  23.         System.out.println(ANSI_CYAN + "\n(нумерация ребер: сначала ребра первой вершины, потом второй и т.д.)");
  24.         System.out.println("(в файле в первой строке должно быть количество вершин, а в каждой\n" +
  25.                 "последующей - инцидентные вершины для каждой вершины, начиная с 1-й)" + ANSI_RESET);
  26.  
  27.         System.out.println("\nВыберите способ ввода: (1 - Консоль) (2 - Файл)");
  28.         System.out.print("Выбор: ");
  29.         int choice = enterNumber(MIN_CHOICE_VALUE, MAX_CHOICE_VALUE);
  30.         IncidenceList incidenceLists = enterIncidenceLists(choice);
  31.  
  32.         System.out.println("Списки инцидентности:");
  33.         System.out.println(incidenceLists.toString());
  34.  
  35.         int[][] incidenceMatrix = incidenceLists.toIncidenceMatrix();
  36.  
  37.         System.out.println("Выберите способ вывода: (1 - Консоль) (2 - Файл)");
  38.         System.out.print("Выбор: ");
  39.         choice = enterNumber(MIN_CHOICE_VALUE, MAX_CHOICE_VALUE);
  40.         displayMatrix(choice, incidenceMatrix);
  41.         scanner.close();
  42.     }
  43.  
  44.     private static IncidenceList enterIncidenceLists(final int choice) {
  45.         IncidenceList incidenceList = new IncidenceList();
  46.  
  47.         if (choice == 1) {
  48.             incidenceList = readListFromConsole();
  49.         } else if (choice == 2) {
  50.             incidenceList = readListFromFile();
  51.         }
  52.  
  53.         return incidenceList;
  54.     }
  55.  
  56.     private static IncidenceList readListFromConsole() {
  57.         ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
  58.  
  59.         System.out.print("\nВведите количество вершин: ");
  60.         int amountVertex = enterNumber(MIN_VALUE, MAX_VALUE);
  61.  
  62.         for (int i = 0; i < amountVertex; i++) {
  63.             System.out.println("Введите список инцидентности " + (i + 1) + "-й вершины: ");
  64.  
  65.             ArrayList<Integer> listOfVertex = checkPrevLists(lists, i + 1);
  66.             for (int j = i + 1; j < amountVertex; j++) {
  67.                 System.out.println("Добавить в список " + (j + 1) + "-ю вершину? (1 - Да) (2 - Нет)");
  68.                 byte choice = enterNumber(MIN_CHOICE_VALUE, MAX_CHOICE_VALUE);
  69.  
  70.                 if (choice == 1) {
  71.                     listOfVertex.add(j + 1);
  72.                 }
  73.             }
  74.  
  75.             lists.add(listOfVertex);
  76.         }
  77.  
  78.         return new IncidenceList(lists);
  79.     }
  80.  
  81.     private static ArrayList<Integer> checkPrevLists(final ArrayList<ArrayList<Integer>> lists, final int currentVertex) {
  82.         ArrayList<Integer> listOfVertex = new ArrayList<>();
  83.  
  84.         for (int i = 0; i < lists.size(); i++) {
  85.             for (int j = 0; j < lists.get(i).size(); j++) {
  86.                 if (lists.get(i).get(j) == currentVertex) {
  87.                     listOfVertex.add(i + 1);
  88.                 }
  89.             }
  90.         }
  91.  
  92.         return listOfVertex;
  93.     }
  94.  
  95.     private static boolean isCorrectLine(String line, final int vertex, final int max) {
  96.         boolean isCorrect = true;
  97.         String[] strArr = line.split(" ");
  98.  
  99.         try {
  100.             for (String strValue: strArr) {
  101.                 int num = Integer.parseInt(strValue);
  102.                 if (num > max || num < 1 || num == vertex) {
  103.                     isCorrect = false;
  104.                 }
  105.             }
  106.         } catch (NumberFormatException e) {
  107.             isCorrect = false;
  108.         }
  109.  
  110.         return isCorrect;
  111.     }
  112.  
  113.     private static boolean isCorrectList(final int numOfList, final ArrayList<Integer> list, final ArrayList<ArrayList<Integer>> incidenceLists) {
  114.         boolean isCorrect = true;
  115.  
  116.         for (int i = 0; i < list.size(); i++) {
  117.             int vertex = list.get(i);
  118.  
  119.             if (numOfList > vertex) {
  120.                 boolean isContains = false;
  121.                 ArrayList<Integer> checkingList = incidenceLists.get(vertex - 1);
  122.                 for (int j = 0; j < checkingList.size(); j++) {
  123.                     if (checkingList.get(j) == numOfList) {
  124.                         isContains = true;
  125.                     }
  126.                 }
  127.  
  128.                 if (!isContains) {
  129.                     isCorrect = false;
  130.                 }
  131.             }
  132.         }
  133.  
  134.         return isCorrect;
  135.     }
  136.  
  137.     private static ArrayList<Integer> getListFromLine(String line) {
  138.         ArrayList<Integer> list = new ArrayList<>();
  139.         String[] strArr = line.split(" ");
  140.  
  141.         for (String num: strArr) {
  142.             list.add(Integer.parseInt(num));
  143.         }
  144.  
  145.         return list;
  146.     }
  147.  
  148.     private static IncidenceList readListFromFile() {
  149.         ArrayList<ArrayList<Integer>> fileList = new ArrayList<>();
  150.         boolean isIncorrect;
  151.  
  152.         System.out.print("\nВведите путь к файлу: ");
  153.         do {
  154.             isIncorrect = false;
  155.             fileList.clear();
  156.  
  157.             String path = enterPathToFile();
  158.             try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
  159.                 String line = reader.readLine();
  160.  
  161.                 if (!(line.matches("^\\d{1,2}") && Integer.parseInt(line) >= MIN_VALUE)) {
  162.                     System.out.print(ANSI_RED + "Ошибка! Кол-во вершин не является целым числом или не входит в диапзон [2; 99]!\n" +
  163.                             ANSI_RESET + "Введите путь к файлу с корректными данными: ");
  164.                     isIncorrect = true;
  165.                 } else {
  166.                     int amountVertexes = Integer.parseInt(line);
  167.                     int numOfList = 0;
  168.  
  169.                     while ((line = reader.readLine()) != null && !isIncorrect) {
  170.                         numOfList++;
  171.  
  172.                         if (isCorrectLine(line, numOfList, amountVertexes)) {
  173.                             ArrayList<Integer> list = getListFromLine(line);
  174.                             if (isCorrectList(numOfList, list, fileList)) {
  175.                                 fileList.add(list);
  176.                             } else {
  177.                                 System.out.print(ANSI_RED + "Ошибка! Списки инцидентности составлены неправильно!" +
  178.                                         ANSI_RESET + "\nВведите путь к файлу с корректными данными: ");
  179.                                 isIncorrect = true;
  180.                             }
  181.                         } else {
  182.                             System.out.print(ANSI_RED + "Ошибка! Списки инцидентности составлены неправильно!" +
  183.                                     ANSI_RESET + "\nВведите путь к файлу с корректными данными: ");
  184.                             isIncorrect = true;
  185.                         }
  186.                     }
  187.  
  188.                     if (!isIncorrect && amountVertexes != numOfList) {
  189.                         System.out.print(ANSI_RED + "Ошибка! Кол-во вершин и списков не совпадает!" +
  190.                                 ANSI_RESET + "\nВведите путь к файлу с корректными данными: ");
  191.                         isIncorrect = true;
  192.                     }
  193.                 }
  194.             } catch (IOException e) {
  195.                 System.out.print(ANSI_RED + "Ошибка ввода! " + ANSI_RESET + "Введите путь к файлу с корректными данными: ");
  196.                 isIncorrect = true;
  197.             }
  198.         } while (isIncorrect);
  199.  
  200.         return new IncidenceList(fileList);
  201.     }
  202.  
  203.     private static byte enterNumber(final int min, final int max) {
  204.         boolean isIncorrect;
  205.         byte num = 0;
  206.  
  207.         do {
  208.             isIncorrect = false;
  209.             try {
  210.                 num = Byte.parseByte(scanner.nextLine());
  211.             } catch (NumberFormatException e) {
  212.                 System.out.print(ANSI_RED + "Ошибка! " + ANSI_RESET + "Введите целое натуральное число: ");
  213.                 isIncorrect = true;
  214.             }
  215.  
  216.             if (!isIncorrect && (num > max || num < min)) {
  217.                 System.out.print(ANSI_RED + "Ошибка! " + ANSI_RESET + "Введите число в диапазоне [" + min + "; " + max + "]: ");
  218.                 isIncorrect = true;
  219.             }
  220.  
  221.         } while (isIncorrect);
  222.  
  223.         return num;
  224.     }
  225.  
  226.     private static void displayMatrix(final int choice, final int[][] matrix) {
  227.         if (choice == 1) {
  228.             displayMatrixToConsole(matrix);
  229.         } else if (choice == 2) {
  230.             saveMatrixToFile(matrix);
  231.         }
  232.     }
  233.  
  234.     private static void saveMatrixToFile(final int[][] matrix) {
  235.         boolean isIncorrect;
  236.  
  237.         System.out.print("Введите путь к файлу: ");
  238.         do {
  239.             isIncorrect = false;
  240.  
  241.             String path = enterPathToFile();
  242.             try (BufferedWriter bufWriter = new BufferedWriter(new FileWriter(path))) {
  243.                 bufWriter.write("Матрица инциденций: \n");
  244.  
  245.                 for (int i = 0; i < matrix.length; i++) {
  246.                     for (int j = 0; j < matrix.length; j++) {
  247.                         bufWriter.write(matrix[i][j] + " ");
  248.                     }
  249.                     bufWriter.write("\n");
  250.                 }
  251.             } catch (IOException e) {
  252.                 System.out.print(ANSI_RED + "Ошибка доступа! " + ANSI_RESET + "Введите путь к доступному файлу: ");
  253.                 isIncorrect = true;
  254.             }
  255.         } while (isIncorrect);
  256.  
  257.         System.out.println("\nРезультат успешно записан в файл!");
  258.     }
  259.  
  260.     private static void displayMatrixToConsole(final int[][] matrix) {
  261.         System.out.println("Матрица инциденций: ");
  262.  
  263.         for (int i = 0; i < matrix.length; i++) {
  264.             for (int j = 0; j < matrix[i].length; j++) {
  265.                 System.out.print(matrix[i][j] + " ");
  266.             }
  267.             System.out.println();
  268.         }
  269.     }
  270.  
  271.     private static String enterPathToFile() {
  272.         boolean isIncorrect;
  273.         String path;
  274.  
  275.         do {
  276.             isIncorrect = false;
  277.             path = scanner.nextLine();
  278.  
  279.             File textFile = new File(path);
  280.             if (!textFile.exists()) {
  281.                 System.out.print(ANSI_RED + "Ошибка! Файл не существует! " + ANSI_RESET + "Повторите ввод: ");
  282.                 isIncorrect = true;
  283.             }
  284.  
  285.             if (!isIncorrect && !path.endsWith(".txt")) {
  286.                 System.out.print(ANSI_RED + "Ошибка! Файл не является текстовым! " + ANSI_RESET + "Повторите ввод: ");
  287.                 isIncorrect = true;
  288.             }
  289.         } while (isIncorrect);
  290.  
  291.         return path;
  292.     }
  293.  
  294. }
  295.  
  296. package com.company;
  297.  
  298. import java.util.ArrayList;
  299.  
  300. public class IncidenceList {
  301.  
  302.     private ArrayList<ArrayList<Integer>> list;
  303.  
  304.     public IncidenceList() {
  305.         this.list = new ArrayList<>();
  306.     }
  307.  
  308.     public IncidenceList(final ArrayList<ArrayList<Integer>> list) {
  309.         this.list = list;
  310.     }
  311.  
  312.     public int size() {
  313.         return this.list.size();
  314.     }
  315.  
  316.     public boolean isEmpty() {
  317.         return list.size() == 0;
  318.     }
  319.  
  320.     public String toString() {
  321.         StringBuilder sb = new StringBuilder();
  322.         if (!isEmpty()) {
  323.             for (int i = 0; i < list.size(); i++) {
  324.                 sb.append(i + 1).append(": ");
  325.                 ArrayList<Integer> cols = list.get(i);
  326.                 for (int j = 0; j < cols.size(); j++) {
  327.                     sb.append(cols.get(j)).append(" -> ");
  328.                 }
  329.                 if (sb.toString().endsWith(" -> ")) {
  330.                     sb.delete(sb.length() - 4, sb.length());
  331.                 }
  332.                 sb.append("\n");
  333.             }
  334.         } else {
  335.             sb.append("[]");
  336.         }
  337.         return  sb.toString();
  338.     }
  339.  
  340.     public int[][] toIncidenceMatrix() {
  341.         int amountVertexes = list.size();
  342.         int amountEdges = countEdges();
  343.  
  344.         int numberOfEdge = 0;
  345.         int[][] matrix = new int[amountVertexes][amountEdges];
  346.  
  347.         for (int i = 0; i < list.size(); i++) {
  348.             ArrayList<Integer> incidenceList = list.get(i);
  349.             for (int j = 0; j < incidenceList.size(); j++) {
  350.                 int vertex = incidenceList.get(j);
  351.                 if (vertex > i + 1) {
  352.                     matrix[i][numberOfEdge] = 1;
  353.                     matrix[vertex - 1][numberOfEdge] = 1;
  354.                     numberOfEdge++;
  355.                 }
  356.             }
  357.         }
  358.         return matrix;
  359.     }
  360.  
  361.     private int countEdges() {
  362.         int edges = 0;
  363.         for (int i = 0; i < list.size(); i++) {
  364.             ArrayList<Integer> incidenceList = list.get(i);
  365.             for (int j = 0; j < incidenceList.size(); j++) {
  366.                 if (incidenceList.get(j) > i + 1)  {
  367.                     edges++;
  368.                 }
  369.             }
  370.         }
  371.         return edges;
  372.     }
  373. }
  374.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement