Advertisement
fatalryuu

Untitled

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